Fossil SCM

Update the built-in SQLite to version 3.6.14.

drh 2009-05-07 00:47 trunk
Commit b4ec5750c690ab2cfb9df61d5b3e92a6623837dd
2 files changed +2478 -1808 +136 -106
+2478 -1808
--- 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.6.13. By combining all the individual C code files into this
3
+** version 3.6.14. 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.
@@ -9,17 +9,17 @@
99
**
1010
** This file is all you need to compile SQLite. To use SQLite in other
1111
** programs, you need this file and the "sqlite3.h" header file that defines
1212
** the programming interface to the SQLite library. (If you do not have
1313
** the "sqlite3.h" header file at hand, you will find a copy in the first
14
-** 5503 lines past this header comment.) Additional code files may be
14
+** 5533 lines past this header comment.) Additional code files may be
1515
** needed if you want a wrapper to interface SQLite with your choice of
1616
** programming language. The code for the "sqlite3" command-line shell
1717
** is also in a separate file. This file contains only code for the core
1818
** SQLite library.
1919
**
20
-** This amalgamation was generated on 2009-04-13 09:47:15 UTC.
20
+** This amalgamation was generated on 2009-05-07 00:36:11 UTC.
2121
*/
2222
#define SQLITE_CORE 1
2323
#define SQLITE_AMALGAMATION 1
2424
#ifndef SQLITE_PRIVATE
2525
# define SQLITE_PRIVATE static
@@ -39,11 +39,11 @@
3939
** May you share freely, never taking more than you give.
4040
**
4141
*************************************************************************
4242
** Internal interface definitions for SQLite.
4343
**
44
-** @(#) $Id: sqliteInt.h,v 1.854 2009/04/08 13:51:51 drh Exp $
44
+** @(#) $Id: sqliteInt.h,v 1.868 2009/05/04 11:42:30 danielk1977 Exp $
4545
*/
4646
#ifndef _SQLITEINT_H_
4747
#define _SQLITEINT_H_
4848
4949
/*
@@ -367,14 +367,14 @@
367367
defined(SQLITE_POW2_MEMORY_SIZE)==0
368368
# define SQLITE_SYSTEM_MALLOC 1
369369
#endif
370370
371371
/*
372
-** If SQLITE_MALLOC_SOFT_LIMIT is defined, then try to keep the
372
+** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
373373
** sizes of memory allocations below this value where possible.
374374
*/
375
-#if defined(SQLITE_POW2_MEMORY_SIZE) && !defined(SQLITE_MALLOC_SOFT_LIMIT)
375
+#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
376376
# define SQLITE_MALLOC_SOFT_LIMIT 1024
377377
#endif
378378
379379
/*
380380
** We need to define _XOPEN_SOURCE as follows in order to enable
@@ -441,10 +441,24 @@
441441
# define TESTONLY(X) X
442442
#else
443443
# define TESTONLY(X)
444444
#endif
445445
446
+/*
447
+** Sometimes we need a small amount of code such as a variable initialization
448
+** to setup for a later assert() statement. We do not want this code to
449
+** appear when assert() is disabled. The following macro is therefore
450
+** used to contain that setup code. The "VVA" acronym stands for
451
+** "Verification, Validation, and Accreditation". In other words, the
452
+** code within VVA_ONLY() will only run during verification processes.
453
+*/
454
+#ifndef NDEBUG
455
+# define VVA_ONLY(X) X
456
+#else
457
+# define VVA_ONLY(X)
458
+#endif
459
+
446460
/*
447461
** The ALWAYS and NEVER macros surround boolean expressions which
448462
** are intended to always be true or false, respectively. Such
449463
** expressions could be omitted from the code completely. But they
450464
** are included in a few cases in order to enhance the resilience
@@ -482,24 +496,10 @@
482496
#else
483497
# define likely(X) !!(X)
484498
# define unlikely(X) !!(X)
485499
#endif
486500
487
-/*
488
-** Sometimes we need a small amount of code such as a variable initialization
489
-** to setup for a later assert() statement. We do not want this code to
490
-** appear when assert() is disabled. The following macro is therefore
491
-** used to contain that setup code. The "VVA" acronym stands for
492
-** "Verification, Validation, and Accreditation". In other words, the
493
-** code within VVA_ONLY() will only run during verification processes.
494
-*/
495
-#ifndef NDEBUG
496
-# define VVA_ONLY(X) X
497
-#else
498
-# define VVA_ONLY(X)
499
-#endif
500
-
501501
/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
502502
/************** Begin file sqlite3.h *****************************************/
503503
/*
504504
** 2001 September 15
505505
**
@@ -530,11 +530,11 @@
530530
** The name of this file under configuration management is "sqlite.h.in".
531531
** The makefile makes some minor changes to this file (such as inserting
532532
** the version number) and changes its name to "sqlite3.h" as
533533
** part of the build process.
534534
**
535
-** @(#) $Id: sqlite.h.in,v 1.440 2009/04/06 15:55:04 drh Exp $
535
+** @(#) $Id: sqlite.h.in,v 1.447 2009/04/30 15:59:56 drh Exp $
536536
*/
537537
#ifndef _SQLITE3_H_
538538
#define _SQLITE3_H_
539539
#include <stdarg.h> /* Needed for the definition of va_list */
540540
@@ -599,12 +599,12 @@
599599
**
600600
** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
601601
**
602602
** Requirements: [H10011] [H10014]
603603
*/
604
-#define SQLITE_VERSION "3.6.13"
605
-#define SQLITE_VERSION_NUMBER 3006013
604
+#define SQLITE_VERSION "3.6.14"
605
+#define SQLITE_VERSION_NUMBER 3006014
606606
607607
/*
608608
** CAPI3REF: Run-Time Library Version Numbers {H10020} <S60100>
609609
** KEYWORDS: sqlite3_version
610610
**
@@ -1291,10 +1291,15 @@
12911291
** the process, or if it is the first time sqlite3_initialize() is invoked
12921292
** following a call to sqlite3_shutdown(). Only an effective call
12931293
** of sqlite3_initialize() does any initialization. All other calls
12941294
** are harmless no-ops.
12951295
**
1296
+** A call to sqlite3_shutdown() is an "effective" call if it is the first
1297
+** call to sqlite3_shutdown() since the last sqlite3_initialize(). Only
1298
+** an effective call to sqlite3_shutdown() does any deinitialization.
1299
+** All other calls to sqlite3_shutdown() are harmless no-ops.
1300
+**
12961301
** Among other things, sqlite3_initialize() shall invoke
12971302
** sqlite3_os_init(). Similarly, sqlite3_shutdown()
12981303
** shall invoke sqlite3_os_end().
12991304
**
13001305
** The sqlite3_initialize() routine returns [SQLITE_OK] on success.
@@ -1717,19 +1722,23 @@
17171722
** on the [database connection] specified by the first parameter.
17181723
** Only changes that are directly specified by the [INSERT], [UPDATE],
17191724
** or [DELETE] statement are counted. Auxiliary changes caused by
17201725
** triggers are not counted. Use the [sqlite3_total_changes()] function
17211726
** to find the total number of changes including changes caused by triggers.
1727
+**
1728
+** Changes to a view that are simulated by an [INSTEAD OF trigger]
1729
+** are not counted. Only real table changes are counted.
17221730
**
17231731
** A "row change" is a change to a single row of a single table
17241732
** caused by an INSERT, DELETE, or UPDATE statement. Rows that
1725
-** are changed as side effects of REPLACE constraint resolution,
1726
-** rollback, ABORT processing, DROP TABLE, or by any other
1733
+** are changed as side effects of [REPLACE] constraint resolution,
1734
+** rollback, ABORT processing, [DROP TABLE], or by any other
17271735
** mechanisms do not count as direct row changes.
17281736
**
17291737
** A "trigger context" is a scope of execution that begins and
1730
-** ends with the script of a trigger. Most SQL statements are
1738
+** ends with the script of a [CREATE TRIGGER | trigger].
1739
+** Most SQL statements are
17311740
** evaluated outside of any trigger. This is the "top level"
17321741
** trigger context. If a trigger fires from the top level, a
17331742
** new trigger context is entered for the duration of that one
17341743
** trigger. Subtriggers create subcontexts for their duration.
17351744
**
@@ -1747,20 +1756,12 @@
17471756
** changes in the most recently completed INSERT, UPDATE, or DELETE
17481757
** statement within the body of the same trigger.
17491758
** However, the number returned does not include changes
17501759
** caused by subtriggers since those have their own context.
17511760
**
1752
-** SQLite implements the command "DELETE FROM table" without a WHERE clause
1753
-** by dropping and recreating the table. Doing so is much faster than going
1754
-** through and deleting individual elements from the table. Because of this
1755
-** optimization, the deletions in "DELETE FROM table" are not row changes and
1756
-** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
1757
-** functions, regardless of the number of elements that were originally
1758
-** in the table. To get an accurate count of the number of rows deleted, use
1759
-** "DELETE FROM table WHERE 1" instead. Or recompile using the
1760
-** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
1761
-** optimization on all queries.
1761
+** See also the [sqlite3_total_changes()] interface and the
1762
+** [count_changes pragma].
17621763
**
17631764
** Requirements:
17641765
** [H12241] [H12243]
17651766
**
17661767
** If a separate thread makes changes on the same database connection
@@ -1770,31 +1771,25 @@
17701771
SQLITE_API int sqlite3_changes(sqlite3*);
17711772
17721773
/*
17731774
** CAPI3REF: Total Number Of Rows Modified {H12260} <S10600>
17741775
**
1775
-** This function returns the number of row changes caused by INSERT,
1776
-** UPDATE or DELETE statements since the [database connection] was opened.
1777
-** The count includes all changes from all trigger contexts. However,
1778
-** the count does not include changes used to implement REPLACE constraints,
1779
-** do rollbacks or ABORT processing, or DROP table processing.
1776
+** This function returns the number of row changes caused by [INSERT],
1777
+** [UPDATE] or [DELETE] statements since the [database connection] was opened.
1778
+** The count includes all changes from all
1779
+** [CREATE TRIGGER | trigger] contexts. However,
1780
+** the count does not include changes used to implement [REPLACE] constraints,
1781
+** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
1782
+** count does not rows of views that fire an [INSTEAD OF trigger], though if
1783
+** the INSTEAD OF trigger makes changes of its own, those changes are
1784
+** counted.
17801785
** The changes are counted as soon as the statement that makes them is
17811786
** completed (when the statement handle is passed to [sqlite3_reset()] or
17821787
** [sqlite3_finalize()]).
17831788
**
1784
-** SQLite implements the command "DELETE FROM table" without a WHERE clause
1785
-** by dropping and recreating the table. (This is much faster than going
1786
-** through and deleting individual elements from the table.) Because of this
1787
-** optimization, the deletions in "DELETE FROM table" are not row changes and
1788
-** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
1789
-** functions, regardless of the number of elements that were originally
1790
-** in the table. To get an accurate count of the number of rows deleted, use
1791
-** "DELETE FROM table WHERE 1" instead. Or recompile using the
1792
-** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
1793
-** optimization on all queries.
1794
-**
1795
-** See also the [sqlite3_changes()] interface.
1789
+** See also the [sqlite3_changes()] interface and the
1790
+** [count_changes pragma].
17961791
**
17971792
** Requirements:
17981793
** [H12261] [H12263]
17991794
**
18001795
** If a separate thread makes changes on the same database connection
@@ -1824,12 +1819,20 @@
18241819
** An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
18251820
** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
18261821
** that is inside an explicit transaction, then the entire transaction
18271822
** will be rolled back automatically.
18281823
**
1829
-** A call to sqlite3_interrupt() has no effect on SQL statements
1830
-** that are started after sqlite3_interrupt() returns.
1824
+** The sqlite3_interrupt(D) call is in effect until all currently running
1825
+** SQL statements on [database connection] D complete. Any new SQL statements
1826
+** that are started after the sqlite3_interrupt() call and before the
1827
+** running statements reaches zero are interrupted as if they had been
1828
+** running prior to the sqlite3_interrupt() call. New SQL statements
1829
+** that are started after the running statement count reaches zero are
1830
+** not effected by the sqlite3_interrupt().
1831
+** A call to sqlite3_interrupt(D) that occurs when there are no running
1832
+** SQL statements is a no-op and has no effect on SQL statements
1833
+** that are started after the sqlite3_interrupt() call returns.
18311834
**
18321835
** Requirements:
18331836
** [H12271] [H12272]
18341837
**
18351838
** If the database connection closes while [sqlite3_interrupt()]
@@ -1838,23 +1841,33 @@
18381841
SQLITE_API void sqlite3_interrupt(sqlite3*);
18391842
18401843
/*
18411844
** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} <S70200>
18421845
**
1843
-** These routines are useful for command-line input to determine if the
1844
-** currently entered text seems to form complete a SQL statement or
1846
+** These routines are useful during command-line input to determine if the
1847
+** currently entered text seems to form a complete SQL statement or
18451848
** if additional input is needed before sending the text into
1846
-** SQLite for parsing. These routines return true if the input string
1849
+** SQLite for parsing. These routines return 1 if the input string
18471850
** appears to be a complete SQL statement. A statement is judged to be
1848
-** complete if it ends with a semicolon token and is not a fragment of a
1849
-** CREATE TRIGGER statement. Semicolons that are embedded within
1851
+** complete if it ends with a semicolon token and is not a prefix of a
1852
+** well-formed CREATE TRIGGER statement. Semicolons that are embedded within
18501853
** string literals or quoted identifier names or comments are not
18511854
** independent tokens (they are part of the token in which they are
1852
-** embedded) and thus do not count as a statement terminator.
1855
+** embedded) and thus do not count as a statement terminator. Whitespace
1856
+** and comments that follow the final semicolon are ignored.
1857
+**
1858
+** These routines return 0 if the statement is incomplete. If a
1859
+** memory allocation fails, then SQLITE_NOMEM is returned.
18531860
**
18541861
** These routines do not parse the SQL statements thus
18551862
** will not detect syntactically incorrect SQL.
1863
+**
1864
+** If SQLite has not been initialized using [sqlite3_initialize()] prior
1865
+** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
1866
+** automatically by sqlite3_complete16(). If that initialization fails,
1867
+** then the return value from sqlite3_complete16() will be non-zero
1868
+** regardless of whether or not the input SQL is complete.
18561869
**
18571870
** Requirements: [H10511] [H10512]
18581871
**
18591872
** The input to [sqlite3_complete()] must be a zero-terminated
18601873
** UTF-8 string.
@@ -2279,25 +2292,30 @@
22792292
**
22802293
** When the callback returns [SQLITE_OK], that means the operation
22812294
** requested is ok. When the callback returns [SQLITE_DENY], the
22822295
** [sqlite3_prepare_v2()] or equivalent call that triggered the
22832296
** authorizer will fail with an error message explaining that
2284
-** access is denied. If the authorizer code is [SQLITE_READ]
2285
-** and the callback returns [SQLITE_IGNORE] then the
2286
-** [prepared statement] statement is constructed to substitute
2287
-** a NULL value in place of the table column that would have
2288
-** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
2289
-** return can be used to deny an untrusted user access to individual
2290
-** columns of a table.
2297
+** access is denied.
22912298
**
22922299
** The first parameter to the authorizer callback is a copy of the third
22932300
** parameter to the sqlite3_set_authorizer() interface. The second parameter
22942301
** to the callback is an integer [SQLITE_COPY | action code] that specifies
22952302
** the particular action to be authorized. The third through sixth parameters
22962303
** to the callback are zero-terminated strings that contain additional
22972304
** details about the action to be authorized.
22982305
**
2306
+** If the action code is [SQLITE_READ]
2307
+** and the callback returns [SQLITE_IGNORE] then the
2308
+** [prepared statement] statement is constructed to substitute
2309
+** a NULL value in place of the table column that would have
2310
+** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
2311
+** return can be used to deny an untrusted user access to individual
2312
+** columns of a table.
2313
+** If the action code is [SQLITE_DELETE] and the callback returns
2314
+** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2315
+** [truncate optimization] is disabled and all rows are deleted individually.
2316
+**
22992317
** An authorizer is used when [sqlite3_prepare | preparing]
23002318
** SQL statements from an untrusted source, to ensure that the SQL statements
23012319
** do not try to access data they are not allowed to see, or that they do not
23022320
** try to execute malicious statements that damage the database. For
23032321
** example, an application may allow a user to enter arbitrary
@@ -2327,11 +2345,13 @@
23272345
** schema change. Hence, the application should ensure that the
23282346
** correct authorizer callback remains in place during the [sqlite3_step()].
23292347
**
23302348
** Note that the authorizer callback is invoked only during
23312349
** [sqlite3_prepare()] or its variants. Authorization is not
2332
-** performed during statement evaluation in [sqlite3_step()].
2350
+** performed during statement evaluation in [sqlite3_step()], unless
2351
+** as stated in the previous paragraph, sqlite3_step() invokes
2352
+** sqlite3_prepare_v2() to reprepare a statement after a schema change.
23332353
**
23342354
** Requirements:
23352355
** [H12501] [H12502] [H12503] [H12504] [H12505] [H12506] [H12507] [H12510]
23362356
** [H12511] [H12512] [H12520] [H12521] [H12522]
23372357
*/
@@ -3983,16 +4003,18 @@
39834003
** for sqlite3_create_collation() and sqlite3_create_collation_v2()
39844004
** and a UTF-16 string for sqlite3_create_collation16(). In all cases
39854005
** the name is passed as the second function argument.
39864006
**
39874007
** The third argument may be one of the constants [SQLITE_UTF8],
3988
-** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
4008
+** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
39894009
** routine expects to be passed pointers to strings encoded using UTF-8,
39904010
** UTF-16 little-endian, or UTF-16 big-endian, respectively. The
3991
-** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
4011
+** third argument might also be [SQLITE_UTF16] to indicate that the routine
4012
+** expects pointers to be UTF-16 strings in the native byte order, or the
4013
+** argument can be [SQLITE_UTF16_ALIGNED] if the
39924014
** the routine expects pointers to 16-bit word aligned strings
3993
-** of UTF-16 in the native byte order of the host computer.
4015
+** of UTF-16 in the native byte order.
39944016
**
39954017
** A pointer to the user supplied routine must be passed as the fifth
39964018
** argument. If it is NULL, this is the same as deleting the collation
39974019
** sequence (so that SQLite cannot call it anymore).
39984020
** Each time the application supplied function is invoked, it is passed
@@ -4012,10 +4034,12 @@
40124034
** destroyed and is passed a copy of the fourth parameter void* pointer
40134035
** of the sqlite3_create_collation_v2().
40144036
** Collations are destroyed when they are overridden by later calls to the
40154037
** collation creation functions or when the [database connection] is closed
40164038
** using [sqlite3_close()].
4039
+**
4040
+** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
40174041
**
40184042
** Requirements:
40194043
** [H16603] [H16604] [H16606] [H16609] [H16612] [H16615] [H16618] [H16621]
40204044
** [H16624] [H16627] [H16630]
40214045
*/
@@ -4566,19 +4590,24 @@
45664590
typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
45674591
typedef struct sqlite3_module sqlite3_module;
45684592
45694593
/*
45704594
** CAPI3REF: Virtual Table Object {H18000} <S20400>
4571
-** KEYWORDS: sqlite3_module
4595
+** KEYWORDS: sqlite3_module {virtual table module}
45724596
** EXPERIMENTAL
45734597
**
4574
-** A module is a class of virtual tables. Each module is defined
4575
-** by an instance of the following structure. This structure consists
4576
-** mostly of methods for the module.
4598
+** This structure, sometimes called a a "virtual table module",
4599
+** defines the implementation of a [virtual tables].
4600
+** This structure consists mostly of methods for the module.
45774601
**
4578
-** This interface is experimental and is subject to change or
4579
-** removal in future releases of SQLite.
4602
+** A virtual table module is created by filling in a persistent
4603
+** instance of this structure and passing a pointer to that instance
4604
+** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
4605
+** The registration remains valid until it is replaced by a different
4606
+** module or until the [database connection] closes. The content
4607
+** of this structure must not change while it is registered with
4608
+** any database connection.
45804609
*/
45814610
struct sqlite3_module {
45824611
int iVersion;
45834612
int (*xCreate)(sqlite3*, void *pAux,
45844613
int argc, const char *const*argv,
@@ -4612,12 +4641,12 @@
46124641
** CAPI3REF: Virtual Table Indexing Information {H18100} <S20400>
46134642
** KEYWORDS: sqlite3_index_info
46144643
** EXPERIMENTAL
46154644
**
46164645
** The sqlite3_index_info structure and its substructures is used to
4617
-** pass information into and receive the reply from the xBestIndex
4618
-** method of an sqlite3_module. The fields under **Inputs** are the
4646
+** pass information into and receive the reply from the [xBestIndex]
4647
+** method of a [virtual table module]. The fields under **Inputs** are the
46194648
** inputs to xBestIndex and are read-only. xBestIndex inserts its
46204649
** results into the **Outputs** fields.
46214650
**
46224651
** The aConstraint[] array records WHERE clause constraints of the form:
46234652
**
@@ -4636,31 +4665,30 @@
46364665
** form that refer to the particular virtual table being queried.
46374666
**
46384667
** Information about the ORDER BY clause is stored in aOrderBy[].
46394668
** Each term of aOrderBy records a column of the ORDER BY clause.
46404669
**
4641
-** The xBestIndex method must fill aConstraintUsage[] with information
4670
+** The [xBestIndex] method must fill aConstraintUsage[] with information
46424671
** about what parameters to pass to xFilter. If argvIndex>0 then
46434672
** the right-hand side of the corresponding aConstraint[] is evaluated
46444673
** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit
46454674
** is true, then the constraint is assumed to be fully handled by the
46464675
** virtual table and is not checked again by SQLite.
46474676
**
4648
-** The idxNum and idxPtr values are recorded and passed into xFilter.
4649
-** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
4677
+** The idxNum and idxPtr values are recorded and passed into the
4678
+** [xFilter] method.
4679
+** [sqlite3_free()] is used to free idxPtr if and only iff
4680
+** needToFreeIdxPtr is true.
46504681
**
4651
-** The orderByConsumed means that output from xFilter will occur in
4682
+** The orderByConsumed means that output from [xFilter]/[xNext] will occur in
46524683
** the correct order to satisfy the ORDER BY clause so that no separate
46534684
** sorting step is required.
46544685
**
46554686
** The estimatedCost value is an estimate of the cost of doing the
46564687
** particular lookup. A full scan of a table with N entries should have
46574688
** a cost of N. A binary search of a table of N entries should have a
46584689
** cost of approximately log(N).
4659
-**
4660
-** This interface is experimental and is subject to change or
4661
-** removal in future releases of SQLite.
46624690
*/
46634691
struct sqlite3_index_info {
46644692
/* Inputs */
46654693
int nConstraint; /* Number of entries in aConstraint */
46664694
struct sqlite3_index_constraint {
@@ -4694,64 +4722,69 @@
46944722
46954723
/*
46964724
** CAPI3REF: Register A Virtual Table Implementation {H18200} <S20400>
46974725
** EXPERIMENTAL
46984726
**
4699
-** This routine is used to register a new module name with a
4700
-** [database connection]. Module names must be registered before
4701
-** creating new virtual tables on the module, or before using
4702
-** preexisting virtual tables of the module.
4727
+** This routine is used to register a new [virtual table module] name.
4728
+** Module names must be registered before
4729
+** creating a new [virtual table] using the module, or before using a
4730
+** preexisting [virtual table] for the module.
47034731
**
4704
-** This interface is experimental and is subject to change or
4705
-** removal in future releases of SQLite.
4732
+** The module name is registered on the [database connection] specified
4733
+** by the first parameter. The name of the module is given by the
4734
+** second parameter. The third parameter is a pointer to
4735
+** the implementation of the [virtual table module]. The fourth
4736
+** parameter is an arbitrary client data pointer that is passed through
4737
+** into the [xCreate] and [xConnect] methods of the virtual table module
4738
+** when a new virtual table is be being created or reinitialized.
4739
+**
4740
+** This interface has exactly the same effect as calling
4741
+** [sqlite3_create_module_v2()] with a NULL client data destructor.
47064742
*/
47074743
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
47084744
sqlite3 *db, /* SQLite connection to register module with */
47094745
const char *zName, /* Name of the module */
4710
- const sqlite3_module *, /* Methods for the module */
4711
- void * /* Client data for xCreate/xConnect */
4746
+ const sqlite3_module *p, /* Methods for the module */
4747
+ void *pClientData /* Client data for xCreate/xConnect */
47124748
);
47134749
47144750
/*
47154751
** CAPI3REF: Register A Virtual Table Implementation {H18210} <S20400>
47164752
** EXPERIMENTAL
47174753
**
4718
-** This routine is identical to the [sqlite3_create_module()] method above,
4719
-** except that it allows a destructor function to be specified. It is
4720
-** even more experimental than the rest of the virtual tables API.
4754
+** This routine is identical to the [sqlite3_create_module()] method,
4755
+** except that it has an extra parameter to specify
4756
+** a destructor function for the client data pointer. SQLite will
4757
+** invoke the destructor function (if it is not NULL) when SQLite
4758
+** no longer needs the pClientData pointer.
47214759
*/
47224760
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
47234761
sqlite3 *db, /* SQLite connection to register module with */
47244762
const char *zName, /* Name of the module */
4725
- const sqlite3_module *, /* Methods for the module */
4726
- void *, /* Client data for xCreate/xConnect */
4763
+ const sqlite3_module *p, /* Methods for the module */
4764
+ void *pClientData, /* Client data for xCreate/xConnect */
47274765
void(*xDestroy)(void*) /* Module destructor function */
47284766
);
47294767
47304768
/*
47314769
** CAPI3REF: Virtual Table Instance Object {H18010} <S20400>
47324770
** KEYWORDS: sqlite3_vtab
47334771
** EXPERIMENTAL
47344772
**
4735
-** Every module implementation uses a subclass of the following structure
4736
-** to describe a particular instance of the module. Each subclass will
4773
+** Every [virtual table module] implementation uses a subclass
4774
+** of the following structure to describe a particular instance
4775
+** of the [virtual table]. Each subclass will
47374776
** be tailored to the specific needs of the module implementation.
47384777
** The purpose of this superclass is to define certain fields that are
47394778
** common to all module implementations.
47404779
**
47414780
** Virtual tables methods can set an error message by assigning a
47424781
** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
47434782
** take care that any prior string is freed by a call to [sqlite3_free()]
47444783
** prior to assigning a new string to zErrMsg. After the error message
47454784
** is delivered up to the client application, the string will be automatically
4746
-** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note
4747
-** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
4748
-** since virtual tables are commonly implemented in loadable extensions which
4749
-** do not have access to sqlite3MPrintf() or sqlite3Free().
4750
-**
4751
-** This interface is experimental and is subject to change or
4752
-** removal in future releases of SQLite.
4785
+** freed by sqlite3_free() and the zErrMsg field will be zeroed.
47534786
*/
47544787
struct sqlite3_vtab {
47554788
const sqlite3_module *pModule; /* The module for this virtual table */
47564789
int nRef; /* Used internally */
47574790
char *zErrMsg; /* Error message from sqlite3_mprintf() */
@@ -4758,24 +4791,25 @@
47584791
/* Virtual table implementations will typically add additional fields */
47594792
};
47604793
47614794
/*
47624795
** CAPI3REF: Virtual Table Cursor Object {H18020} <S20400>
4763
-** KEYWORDS: sqlite3_vtab_cursor
4796
+** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
47644797
** EXPERIMENTAL
47654798
**
4766
-** Every module implementation uses a subclass of the following structure
4767
-** to describe cursors that point into the virtual table and are used
4799
+** Every [virtual table module] implementation uses a subclass of the
4800
+** following structure to describe cursors that point into the
4801
+** [virtual table] and are used
47684802
** to loop through the virtual table. Cursors are created using the
4769
-** xOpen method of the module. Each module implementation will define
4803
+** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
4804
+** by the [sqlite3_module.xClose | xClose] method. Cussors are used
4805
+** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
4806
+** of the module. Each module implementation will define
47704807
** the content of a cursor structure to suit its own needs.
47714808
**
47724809
** This superclass exists in order to define fields of the cursor that
47734810
** are common to all implementations.
4774
-**
4775
-** This interface is experimental and is subject to change or
4776
-** removal in future releases of SQLite.
47774811
*/
47784812
struct sqlite3_vtab_cursor {
47794813
sqlite3_vtab *pVtab; /* Virtual table of this cursor */
47804814
/* Virtual table implementations will typically add additional fields */
47814815
};
@@ -4782,37 +4816,33 @@
47824816
47834817
/*
47844818
** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} <S20400>
47854819
** EXPERIMENTAL
47864820
**
4787
-** The xCreate and xConnect methods of a module use the following API
4821
+** The [xCreate] and [xConnect] methods of a
4822
+** [virtual table module] call this interface
47884823
** to declare the format (the names and datatypes of the columns) of
47894824
** the virtual tables they implement.
4790
-**
4791
-** This interface is experimental and is subject to change or
4792
-** removal in future releases of SQLite.
47934825
*/
4794
-SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
4826
+SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
47954827
47964828
/*
47974829
** CAPI3REF: Overload A Function For A Virtual Table {H18300} <S20400>
47984830
** EXPERIMENTAL
47994831
**
48004832
** Virtual tables can provide alternative implementations of functions
4801
-** using the xFindFunction method. But global versions of those functions
4833
+** using the [xFindFunction] method of the [virtual table module].
4834
+** But global versions of those functions
48024835
** must exist in order to be overloaded.
48034836
**
48044837
** This API makes sure a global version of a function with a particular
48054838
** name and number of parameters exists. If no such function exists
48064839
** before this API is called, a new function is created. The implementation
48074840
** of the new function always causes an exception to be thrown. So
48084841
** the new function is not good for anything by itself. Its only
48094842
** purpose is to be a placeholder function that can be overloaded
4810
-** by virtual tables.
4811
-**
4812
-** This API should be considered part of the virtual table interface,
4813
-** which is experimental and subject to change.
4843
+** by a [virtual table].
48144844
*/
48154845
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
48164846
48174847
/*
48184848
** The interface to the virtual-table mechanism defined above (back up
@@ -6020,11 +6050,11 @@
60206050
**
60216051
*************************************************************************
60226052
** This is the header file for the generic hash-table implemenation
60236053
** used in SQLite.
60246054
**
6025
-** $Id: hash.h,v 1.12 2008/10/10 17:41:29 drh Exp $
6055
+** $Id: hash.h,v 1.15 2009/05/02 13:29:38 drh Exp $
60266056
*/
60276057
#ifndef _SQLITE_HASH_H_
60286058
#define _SQLITE_HASH_H_
60296059
60306060
/* Forward declarations of structures. */
@@ -6033,17 +6063,29 @@
60336063
60346064
/* A complete hash table is an instance of the following structure.
60356065
** The internals of this structure are intended to be opaque -- client
60366066
** code should not attempt to access or modify the fields of this structure
60376067
** directly. Change this structure only by using the routines below.
6038
-** However, many of the "procedures" and "functions" for modifying and
6068
+** However, some of the "procedures" and "functions" for modifying and
60396069
** accessing this structure are really macros, so we can't really make
60406070
** this structure opaque.
6071
+**
6072
+** All elements of the hash table are on a single doubly-linked list.
6073
+** Hash.first points to the head of this list.
6074
+**
6075
+** There are Hash.htsize buckets. Each bucket points to a spot in
6076
+** the global doubly-linked list. The contents of the bucket are the
6077
+** element pointed to plus the next _ht.count-1 elements in the list.
6078
+**
6079
+** Hash.htsize and Hash.ht may be zero. In that case lookup is done
6080
+** by a linear search of the global list. For small tables, the
6081
+** Hash.ht table is never allocated because if there are few elements
6082
+** in the table, it is faster to do a linear search than to manage
6083
+** the hash table.
60416084
*/
60426085
struct Hash {
6043
- unsigned int copyKey: 1; /* True if copy of key made on insert */
6044
- unsigned int htsize : 31; /* Number of buckets in the hash table */
6086
+ unsigned int htsize; /* Number of buckets in the hash table */
60456087
unsigned int count; /* Number of entries in this table */
60466088
HashElem *first; /* The first element of the array */
60476089
struct _ht { /* the hash table */
60486090
int count; /* Number of entries with this hash */
60496091
HashElem *chain; /* Pointer to first entry with this hash */
@@ -6055,22 +6097,21 @@
60556097
**
60566098
** Again, this structure is intended to be opaque, but it can't really
60576099
** be opaque because it is used by macros.
60586100
*/
60596101
struct HashElem {
6060
- HashElem *next, *prev; /* Next and previous elements in the table */
6061
- void *data; /* Data associated with this element */
6062
- void *pKey; int nKey; /* Key associated with this element */
6102
+ HashElem *next, *prev; /* Next and previous elements in the table */
6103
+ void *data; /* Data associated with this element */
6104
+ const char *pKey; int nKey; /* Key associated with this element */
60636105
};
60646106
60656107
/*
60666108
** Access routines. To delete, insert a NULL pointer.
60676109
*/
6068
-SQLITE_PRIVATE void sqlite3HashInit(Hash*, int copyKey);
6069
-SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
6070
-SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
6071
-SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash*, const void *pKey, int nKey);
6110
+SQLITE_PRIVATE void sqlite3HashInit(Hash*);
6111
+SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
6112
+SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
60726113
SQLITE_PRIVATE void sqlite3HashClear(Hash*);
60736114
60746115
/*
60756116
** Macros for looping over all elements of a hash table. The idiom is
60766117
** like this:
@@ -6084,17 +6125,17 @@
60846125
** }
60856126
*/
60866127
#define sqliteHashFirst(H) ((H)->first)
60876128
#define sqliteHashNext(E) ((E)->next)
60886129
#define sqliteHashData(E) ((E)->data)
6089
-#define sqliteHashKey(E) ((E)->pKey)
6090
-#define sqliteHashKeysize(E) ((E)->nKey)
6130
+/* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
6131
+/* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
60916132
60926133
/*
60936134
** Number of entries in a hash table
60946135
*/
6095
-#define sqliteHashCount(H) ((H)->count)
6136
+/* #define sqliteHashCount(H) ((H)->count) // NOT USED */
60966137
60976138
#endif /* _SQLITE_HASH_H_ */
60986139
60996140
/************** End of hash.h ************************************************/
61006141
/************** Continuing where we left off in sqliteInt.h ******************/
@@ -6592,11 +6633,11 @@
65926633
*************************************************************************
65936634
** This header file defines the interface that the sqlite B-Tree file
65946635
** subsystem. See comments in the source code for a detailed description
65956636
** of what each interface routine does.
65966637
**
6597
-** @(#) $Id: btree.h,v 1.113 2009/04/10 12:55:17 danielk1977 Exp $
6638
+** @(#) $Id: btree.h,v 1.114 2009/05/04 11:42:30 danielk1977 Exp $
65986639
*/
65996640
#ifndef _BTREE_H_
66006641
#define _BTREE_H_
66016642
66026643
/* TODO: This definition is just included so other modules compile. It
@@ -6727,11 +6768,11 @@
67276768
);
67286769
SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
67296770
SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
67306771
SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
67316772
const void *pData, int nData,
6732
- int nZero, int bias);
6773
+ int nZero, int bias, int seekResult);
67336774
SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
67346775
SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
67356776
SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
67366777
SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
67376778
SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor*);
@@ -6973,110 +7014,110 @@
69737014
#define OP_OpenWrite 10
69747015
#define OP_NotNull 72 /* same as TK_NOTNULL */
69757016
#define OP_If 11
69767017
#define OP_ToInt 144 /* same as TK_TO_INT */
69777018
#define OP_String8 94 /* same as TK_STRING */
6978
-#define OP_VRowid 12
6979
-#define OP_CollSeq 13
6980
-#define OP_OpenRead 14
6981
-#define OP_Expire 15
6982
-#define OP_AutoCommit 16
7019
+#define OP_CollSeq 12
7020
+#define OP_OpenRead 13
7021
+#define OP_Expire 14
7022
+#define OP_AutoCommit 15
69837023
#define OP_Gt 75 /* same as TK_GT */
6984
-#define OP_Pagecount 17
6985
-#define OP_IntegrityCk 18
6986
-#define OP_Sort 20
6987
-#define OP_Copy 21
6988
-#define OP_Trace 22
6989
-#define OP_Function 23
6990
-#define OP_IfNeg 24
7024
+#define OP_Pagecount 16
7025
+#define OP_IntegrityCk 17
7026
+#define OP_Sort 18
7027
+#define OP_Copy 20
7028
+#define OP_Trace 21
7029
+#define OP_Function 22
7030
+#define OP_IfNeg 23
69917031
#define OP_And 67 /* same as TK_AND */
69927032
#define OP_Subtract 85 /* same as TK_MINUS */
6993
-#define OP_Noop 25
6994
-#define OP_Return 26
7033
+#define OP_Noop 24
7034
+#define OP_Return 25
69957035
#define OP_Remainder 88 /* same as TK_REM */
6996
-#define OP_NewRowid 27
7036
+#define OP_NewRowid 26
69977037
#define OP_Multiply 86 /* same as TK_STAR */
6998
-#define OP_Variable 28
6999
-#define OP_String 29
7000
-#define OP_RealAffinity 30
7001
-#define OP_VRename 31
7002
-#define OP_ParseSchema 32
7003
-#define OP_VOpen 33
7004
-#define OP_Close 34
7005
-#define OP_CreateIndex 35
7006
-#define OP_IsUnique 36
7007
-#define OP_NotFound 37
7008
-#define OP_Int64 38
7009
-#define OP_MustBeInt 39
7010
-#define OP_Halt 40
7011
-#define OP_Rowid 41
7012
-#define OP_IdxLT 42
7013
-#define OP_AddImm 43
7014
-#define OP_Statement 44
7015
-#define OP_RowData 45
7016
-#define OP_MemMax 46
7038
+#define OP_Variable 27
7039
+#define OP_String 28
7040
+#define OP_RealAffinity 29
7041
+#define OP_VRename 30
7042
+#define OP_ParseSchema 31
7043
+#define OP_VOpen 32
7044
+#define OP_Close 33
7045
+#define OP_CreateIndex 34
7046
+#define OP_IsUnique 35
7047
+#define OP_NotFound 36
7048
+#define OP_Int64 37
7049
+#define OP_MustBeInt 38
7050
+#define OP_Halt 39
7051
+#define OP_Rowid 40
7052
+#define OP_IdxLT 41
7053
+#define OP_AddImm 42
7054
+#define OP_Statement 43
7055
+#define OP_RowData 44
7056
+#define OP_MemMax 45
70177057
#define OP_Or 66 /* same as TK_OR */
7018
-#define OP_NotExists 47
7019
-#define OP_Gosub 48
7058
+#define OP_NotExists 46
7059
+#define OP_Gosub 47
70207060
#define OP_Divide 87 /* same as TK_SLASH */
7021
-#define OP_Integer 49
7061
+#define OP_Integer 48
70227062
#define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
7023
-#define OP_Prev 50
7024
-#define OP_RowSetRead 51
7063
+#define OP_Prev 49
7064
+#define OP_RowSetRead 50
70257065
#define OP_Concat 89 /* same as TK_CONCAT */
7026
-#define OP_RowSetAdd 52
7066
+#define OP_RowSetAdd 51
70277067
#define OP_BitAnd 80 /* same as TK_BITAND */
7028
-#define OP_VColumn 53
7029
-#define OP_CreateTable 54
7030
-#define OP_Last 55
7031
-#define OP_SeekLe 56
7068
+#define OP_VColumn 52
7069
+#define OP_CreateTable 53
7070
+#define OP_Last 54
7071
+#define OP_SeekLe 55
70327072
#define OP_IsNull 71 /* same as TK_ISNULL */
7033
-#define OP_IncrVacuum 57
7034
-#define OP_IdxRowid 58
7073
+#define OP_IncrVacuum 56
7074
+#define OP_IdxRowid 57
70357075
#define OP_ShiftRight 83 /* same as TK_RSHIFT */
7036
-#define OP_ResetCount 59
7037
-#define OP_ContextPush 60
7038
-#define OP_Yield 61
7039
-#define OP_DropTrigger 62
7040
-#define OP_DropIndex 63
7041
-#define OP_IdxGE 64
7042
-#define OP_IdxDelete 65
7043
-#define OP_Vacuum 68
7044
-#define OP_IfNot 69
7045
-#define OP_DropTable 70
7046
-#define OP_SeekLt 79
7047
-#define OP_MakeRecord 90
7076
+#define OP_ResetCount 58
7077
+#define OP_ContextPush 59
7078
+#define OP_Yield 60
7079
+#define OP_DropTrigger 61
7080
+#define OP_DropIndex 62
7081
+#define OP_IdxGE 63
7082
+#define OP_IdxDelete 64
7083
+#define OP_Vacuum 65
7084
+#define OP_IfNot 68
7085
+#define OP_DropTable 69
7086
+#define OP_SeekLt 70
7087
+#define OP_MakeRecord 79
70487088
#define OP_ToBlob 142 /* same as TK_TO_BLOB */
7049
-#define OP_ResultRow 91
7050
-#define OP_Delete 92
7051
-#define OP_AggFinal 95
7052
-#define OP_Compare 96
7089
+#define OP_ResultRow 90
7090
+#define OP_Delete 91
7091
+#define OP_AggFinal 92
7092
+#define OP_Compare 95
70537093
#define OP_ShiftLeft 82 /* same as TK_LSHIFT */
7054
-#define OP_Goto 97
7055
-#define OP_TableLock 98
7056
-#define OP_Clear 99
7094
+#define OP_Goto 96
7095
+#define OP_TableLock 97
7096
+#define OP_Clear 98
70577097
#define OP_Le 76 /* same as TK_LE */
7058
-#define OP_VerifyCookie 100
7059
-#define OP_AggStep 101
7098
+#define OP_VerifyCookie 99
7099
+#define OP_AggStep 100
70607100
#define OP_ToText 141 /* same as TK_TO_TEXT */
70617101
#define OP_Not 19 /* same as TK_NOT */
70627102
#define OP_ToReal 145 /* same as TK_TO_REAL */
7063
-#define OP_SetNumColumns 102
7064
-#define OP_Transaction 103
7065
-#define OP_VFilter 104
7103
+#define OP_SetNumColumns 101
7104
+#define OP_Transaction 102
7105
+#define OP_VFilter 103
70667106
#define OP_Ne 73 /* same as TK_NE */
7067
-#define OP_VDestroy 105
7068
-#define OP_ContextPop 106
7107
+#define OP_VDestroy 104
7108
+#define OP_ContextPop 105
70697109
#define OP_BitOr 81 /* same as TK_BITOR */
7070
-#define OP_Next 107
7071
-#define OP_Count 108
7072
-#define OP_IdxInsert 109
7110
+#define OP_Next 106
7111
+#define OP_Count 107
7112
+#define OP_IdxInsert 108
70737113
#define OP_Lt 77 /* same as TK_LT */
7074
-#define OP_SeekGe 110
7075
-#define OP_Insert 111
7076
-#define OP_Destroy 112
7077
-#define OP_ReadCookie 113
7114
+#define OP_SeekGe 109
7115
+#define OP_Insert 110
7116
+#define OP_Destroy 111
7117
+#define OP_ReadCookie 112
7118
+#define OP_RowSetTest 113
70787119
#define OP_LoadAnalysis 114
70797120
#define OP_Explain 115
70807121
#define OP_HaltIfNull 116
70817122
#define OP_OpenPseudo 117
70827123
#define OP_OpenEphemeral 118
@@ -7117,24 +7158,24 @@
71177158
#define OPFLG_IN2 0x0008 /* in2: P2 is an input */
71187159
#define OPFLG_IN3 0x0010 /* in3: P3 is an input */
71197160
#define OPFLG_OUT3 0x0020 /* out3: P3 is an output */
71207161
#define OPFLG_INITIALIZER {\
71217162
/* 0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x08, 0x02, 0x00,\
7122
-/* 8 */ 0x00, 0x04, 0x00, 0x05, 0x02, 0x00, 0x00, 0x00,\
7123
-/* 16 */ 0x00, 0x02, 0x00, 0x04, 0x01, 0x04, 0x00, 0x00,\
7124
-/* 24 */ 0x05, 0x00, 0x04, 0x02, 0x00, 0x02, 0x04, 0x00,\
7125
-/* 32 */ 0x00, 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05,\
7126
-/* 40 */ 0x00, 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11,\
7127
-/* 48 */ 0x01, 0x02, 0x01, 0x21, 0x08, 0x00, 0x02, 0x01,\
7128
-/* 56 */ 0x11, 0x01, 0x02, 0x00, 0x00, 0x04, 0x00, 0x00,\
7129
-/* 64 */ 0x11, 0x00, 0x2c, 0x2c, 0x00, 0x05, 0x00, 0x05,\
7130
-/* 72 */ 0x05, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x11,\
7163
+/* 8 */ 0x00, 0x04, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00,\
7164
+/* 16 */ 0x02, 0x00, 0x01, 0x04, 0x04, 0x00, 0x00, 0x05,\
7165
+/* 24 */ 0x00, 0x04, 0x02, 0x00, 0x02, 0x04, 0x00, 0x00,\
7166
+/* 32 */ 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05, 0x00,\
7167
+/* 40 */ 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11, 0x01,\
7168
+/* 48 */ 0x02, 0x01, 0x21, 0x08, 0x00, 0x02, 0x01, 0x11,\
7169
+/* 56 */ 0x01, 0x02, 0x00, 0x00, 0x04, 0x00, 0x00, 0x11,\
7170
+/* 64 */ 0x00, 0x00, 0x2c, 0x2c, 0x05, 0x00, 0x11, 0x05,\
7171
+/* 72 */ 0x05, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x00,\
71317172
/* 80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c,\
71327173
/* 88 */ 0x2c, 0x2c, 0x00, 0x00, 0x00, 0x04, 0x02, 0x00,\
7133
-/* 96 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7134
-/* 104 */ 0x01, 0x00, 0x00, 0x01, 0x02, 0x08, 0x11, 0x00,\
7135
-/* 112 */ 0x02, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x02,\
7174
+/* 96 */ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,\
7175
+/* 104 */ 0x00, 0x00, 0x01, 0x02, 0x08, 0x11, 0x00, 0x02,\
7176
+/* 112 */ 0x02, 0x15, 0x00, 0x00, 0x10, 0x00, 0x00, 0x02,\
71367177
/* 120 */ 0x00, 0x02, 0x01, 0x11, 0x00, 0x00, 0x05, 0x00,\
71377178
/* 128 */ 0x11, 0x05, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00,\
71387179
/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
71397180
/* 144 */ 0x04, 0x04,}
71407181
@@ -7216,11 +7257,11 @@
72167257
*************************************************************************
72177258
** This header file defines the interface that the sqlite page cache
72187259
** subsystem. The page cache subsystem reads and writes a file a page
72197260
** at a time and provides a journal for rollback.
72207261
**
7221
-** @(#) $Id: pager.h,v 1.100 2009/02/03 16:51:25 danielk1977 Exp $
7262
+** @(#) $Id: pager.h,v 1.101 2009/04/30 09:10:38 danielk1977 Exp $
72227263
*/
72237264
72247265
#ifndef _PAGER_H_
72257266
#define _PAGER_H_
72267267
@@ -7322,11 +7363,11 @@
73227363
SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
73237364
SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
73247365
73257366
/* Functions used to manage pager transactions and savepoints. */
73267367
SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
7327
-SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag);
7368
+SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
73287369
SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
73297370
SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
73307371
SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
73317372
SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
73327373
SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
@@ -7917,11 +7958,10 @@
79177958
struct Schema {
79187959
int schema_cookie; /* Database schema version number for this file */
79197960
Hash tblHash; /* All tables indexed by name */
79207961
Hash idxHash; /* All (named) indices indexed by name */
79217962
Hash trigHash; /* All triggers indexed by name */
7922
- Hash aFKey; /* Foreign keys indexed by to-table */
79237963
Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
79247964
u8 file_format; /* Schema format version for this file */
79257965
u8 enc; /* Text encoding used by this database */
79267966
u16 flags; /* Flags associated with this schema */
79277967
int cache_size; /* Number of pages to use in the cache */
@@ -8473,32 +8513,25 @@
84738513
**
84748514
** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
84758515
**
84768516
** Each REFERENCES clause generates an instance of the following structure
84778517
** which is attached to the from-table. The to-table need not exist when
8478
-** the from-table is created. The existence of the to-table is not checked
8479
-** until an attempt is made to insert data into the from-table.
8480
-**
8481
-** The sqlite.aFKey hash table stores pointers to this structure
8482
-** given the name of a to-table. For each to-table, all foreign keys
8483
-** associated with that table are on a linked list using the FKey.pNextTo
8484
-** field.
8518
+** the from-table is created. The existence of the to-table is not checked.
84858519
*/
84868520
struct FKey {
84878521
Table *pFrom; /* The table that contains the REFERENCES clause */
84888522
FKey *pNextFrom; /* Next foreign key in pFrom */
84898523
char *zTo; /* Name of table that the key points to */
8490
- FKey *pNextTo; /* Next foreign key that points to zTo */
84918524
int nCol; /* Number of columns in this key */
8492
- struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
8493
- int iFrom; /* Index of column in pFrom */
8494
- char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
8495
- } *aCol; /* One entry for each of nCol column s */
84968525
u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
84978526
u8 updateConf; /* How to resolve conflicts that occur on UPDATE */
84988527
u8 deleteConf; /* How to resolve conflicts that occur on DELETE */
84998528
u8 insertConf; /* How to resolve conflicts that occur on INSERT */
8529
+ struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
8530
+ int iFrom; /* Index of column in pFrom */
8531
+ char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
8532
+ } aCol[1]; /* One entry for each of nCol column s */
85008533
};
85018534
85028535
/*
85038536
** SQLite supports many different ways to resolve a constraint
85048537
** error. ROLLBACK processing means that a constraint violation
@@ -8568,10 +8601,11 @@
85688601
*/
85698602
struct UnpackedRecord {
85708603
KeyInfo *pKeyInfo; /* Collation and sort-order information */
85718604
u16 nField; /* Number of entries in apMem[] */
85728605
u16 flags; /* Boolean settings. UNPACKED_... below */
8606
+ i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
85738607
Mem *aMem; /* Values */
85748608
};
85758609
85768610
/*
85778611
** Allowed values of UnpackedRecord.flags
@@ -8579,10 +8613,11 @@
85798613
#define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */
85808614
#define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */
85818615
#define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */
85828616
#define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */
85838617
#define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */
8618
+#define UNPACKED_PREFIX_SEARCH 0x0020 /* A prefix match is considered OK */
85848619
85858620
/*
85868621
** Each SQL index is represented in memory by an
85878622
** instance of the following structure.
85888623
**
@@ -8632,12 +8667,13 @@
86328667
** may contain random values. Do not make any assumptions about Token.dyn
86338668
** and Token.n when Token.z==0.
86348669
*/
86358670
struct Token {
86368671
const unsigned char *z; /* Text of the token. Not NULL-terminated! */
8637
- unsigned dyn : 1; /* True for malloced memory, false for static */
8638
- unsigned n : 31; /* Number of characters in this token */
8672
+ unsigned dyn : 1; /* True for malloced memory, false for static */
8673
+ unsigned quoted : 1; /* True if token still has its quotes */
8674
+ unsigned n : 30; /* Number of characters in this token */
86398675
};
86408676
86418677
/*
86428678
** An instance of this structure contains information needed to generate
86438679
** code for a SELECT that contains aggregate functions.
@@ -8795,11 +8831,11 @@
87958831
#define EP_Agg 0x0002 /* Contains one or more aggregate functions */
87968832
#define EP_Resolved 0x0004 /* IDs have been resolved to COLUMNs */
87978833
#define EP_Error 0x0008 /* Expression contains one or more errors */
87988834
#define EP_Distinct 0x0010 /* Aggregate function with DISTINCT keyword */
87998835
#define EP_VarSelect 0x0020 /* pSelect is correlated, not constant */
8800
-#define EP_Dequoted 0x0040 /* True if the string has been dequoted */
8836
+#define EP_DblQuoted 0x0040 /* token.z was originally in "..." */
88018837
#define EP_InfixFunc 0x0080 /* True for an infix function: LIKE, GLOB, etc */
88028838
#define EP_ExpCollate 0x0100 /* Collating sequence specified explicitly */
88038839
#define EP_AnyAff 0x0200 /* Can take a cached column of any affinity */
88048840
#define EP_FixedDest 0x0400 /* Result needed in a specific register */
88058841
#define EP_IntValue 0x0800 /* Integer value contained in iTable */
@@ -9020,19 +9056,21 @@
90209056
*/
90219057
sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
90229058
};
90239059
90249060
/*
9025
-** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin().
9061
+** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
9062
+** and the WhereInfo.wctrlFlags member.
90269063
*/
90279064
#define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
90289065
#define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
90299066
#define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
90309067
#define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
9031
-#define WHERE_FILL_ROWSET 0x0008 /* Save results in a RowSet object */
9032
-#define WHERE_OMIT_OPEN 0x0010 /* Table cursor are already open */
9033
-#define WHERE_OMIT_CLOSE 0x0020 /* Omit close of table & index cursors */
9068
+#define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
9069
+#define WHERE_OMIT_OPEN 0x0010 /* Table cursor are already open */
9070
+#define WHERE_OMIT_CLOSE 0x0020 /* Omit close of table & index cursors */
9071
+#define WHERE_FORCE_TABLE 0x0040 /* Do not use an index-only search */
90349072
90359073
/*
90369074
** The WHERE clause processing routine has two halves. The
90379075
** first part does the start of the WHERE loop and the second
90389076
** half does the tail of the WHERE loop. An instance of
@@ -9041,11 +9079,10 @@
90419079
*/
90429080
struct WhereInfo {
90439081
Parse *pParse; /* Parsing and code generating context */
90449082
u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
90459083
u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE or DELETE */
9046
- int regRowSet; /* Store rowids in this rowset if >=0 */
90479084
SrcList *pTabList; /* List of tables in the join */
90489085
int iTop; /* The very beginning of the WHERE loop */
90499086
int iContinue; /* Jump here to continue with next record */
90509087
int iBreak; /* Jump here to break out of the loop */
90519088
int nLevel; /* Number of nested loop */
@@ -9169,10 +9206,17 @@
91699206
int iParm; /* A parameter used by the eDest disposal method */
91709207
int iMem; /* Base register where results are written */
91719208
int nMem; /* Number of registers allocated */
91729209
};
91739210
9211
+/*
9212
+** Size of the column cache
9213
+*/
9214
+#ifndef SQLITE_N_COLCACHE
9215
+# define SQLITE_N_COLCACHE 10
9216
+#endif
9217
+
91749218
/*
91759219
** An SQL parser context. A copy of this structure is passed through
91769220
** the parser and down into all the parser action routine in order to
91779221
** carry around information that is global to the entire parse.
91789222
**
@@ -9205,19 +9249,23 @@
92059249
int nErr; /* Number of errors seen */
92069250
int nTab; /* Number of previously allocated VDBE cursors */
92079251
int nMem; /* Number of memory cells used so far */
92089252
int nSet; /* Number of sets used so far */
92099253
int ckBase; /* Base register of data during check constraints */
9210
- int disableColCache; /* True to disable adding to column cache */
9211
- int nColCache; /* Number of entries in the column cache */
9212
- int iColCache; /* Next entry of the cache to replace */
9254
+ int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
9255
+ int iCacheCnt; /* Counter used to generate aColCache[].lru values */
9256
+ u8 nColCache; /* Number of entries in the column cache */
9257
+ u8 iColCache; /* Next entry of the cache to replace */
92139258
struct yColCache {
92149259
int iTable; /* Table cursor number */
92159260
int iColumn; /* Table column number */
9216
- char affChange; /* True if this register has had an affinity change */
9217
- int iReg; /* Register holding value of this column */
9218
- } aColCache[10]; /* One for each valid column cache entry */
9261
+ u8 affChange; /* True if this register has had an affinity change */
9262
+ u8 tempReg; /* iReg is a temp register that needs to be freed */
9263
+ int iLevel; /* Nesting level */
9264
+ int iReg; /* Reg with value of this column. 0 means none. */
9265
+ int lru; /* Least recently used entry has the smallest value */
9266
+ } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
92199267
u32 writeMask; /* Start a write transaction on these databases */
92209268
u32 cookieMask; /* Bitmask of schema verified databases */
92219269
int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
92229270
int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
92239271
#ifndef SQLITE_OMIT_SHARED_CACHE
@@ -9271,16 +9319,17 @@
92719319
const char *zAuthContext; /* Put saved Parse.zAuthContext here */
92729320
Parse *pParse; /* The Parse structure */
92739321
};
92749322
92759323
/*
9276
-** Bitfield flags for P2 value in OP_Insert and OP_Delete
9324
+** Bitfield flags for P5 value in OP_Insert and OP_Delete
92779325
*/
9278
-#define OPFLAG_NCHANGE 1 /* Set to update db->nChange */
9279
-#define OPFLAG_LASTROWID 2 /* Set to update db->lastRowid */
9280
-#define OPFLAG_ISUPDATE 4 /* This OP_Insert is an sql UPDATE */
9281
-#define OPFLAG_APPEND 8 /* This is likely to be an append */
9326
+#define OPFLAG_NCHANGE 1 /* Set to update db->nChange */
9327
+#define OPFLAG_LASTROWID 2 /* Set to update db->lastRowid */
9328
+#define OPFLAG_ISUPDATE 4 /* This OP_Insert is an sql UPDATE */
9329
+#define OPFLAG_APPEND 8 /* This is likely to be an append */
9330
+#define OPFLAG_USESEEKRESULT 16 /* Try to avoid a seek in BtreeInsert() */
92829331
92839332
/*
92849333
* Each trigger present in the database schema is stored as an instance of
92859334
* struct Trigger.
92869335
*
@@ -9567,11 +9616,10 @@
95679616
** Internal function prototypes
95689617
*/
95699618
SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
95709619
SQLITE_PRIVATE int sqlite3StrNICmp(const char *, const char *, int);
95719620
SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
9572
-SQLITE_PRIVATE int sqlite3Strlen(sqlite3*, const char*);
95739621
SQLITE_PRIVATE int sqlite3Strlen30(const char*);
95749622
95759623
SQLITE_PRIVATE int sqlite3MallocInit(void);
95769624
SQLITE_PRIVATE void sqlite3MallocEnd(void);
95779625
SQLITE_PRIVATE void *sqlite3Malloc(int);
@@ -9626,12 +9674,11 @@
96269674
SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
96279675
#endif
96289676
SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
96299677
SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
96309678
SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
9631
-SQLITE_PRIVATE void sqlite3Dequote(char*);
9632
-SQLITE_PRIVATE void sqlite3DequoteExpr(Expr*);
9679
+SQLITE_PRIVATE int sqlite3Dequote(char*);
96339680
SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
96349681
SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
96359682
SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
96369683
SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
96379684
SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
@@ -9675,10 +9722,11 @@
96759722
SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
96769723
96779724
SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
96789725
SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
96799726
SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
9727
+SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
96809728
SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
96819729
96829730
SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
96839731
96849732
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
@@ -9716,18 +9764,21 @@
97169764
#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
97179765
SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
97189766
#endif
97199767
SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
97209768
SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
9721
-SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u8, int);
9769
+SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
97229770
SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
97239771
SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, int);
97249772
SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
97259773
SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
9726
-SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse*, int);
9774
+SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
9775
+SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
9776
+SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
9777
+SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int);
9778
+SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
97279779
SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
9728
-SQLITE_PRIVATE void sqlite3ExprWritableRegister(Parse*,int);
97299780
SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
97309781
SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
97319782
SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
97329783
SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
97339784
SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
@@ -9765,12 +9816,12 @@
97659816
SQLITE_PRIVATE int sqlite3IsRowid(const char*);
97669817
SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
97679818
SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
97689819
SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
97699820
SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
9770
- int*,int,int,int,int);
9771
-SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
9821
+ int*,int,int,int,int,int*);
9822
+SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int,int,int);
97729823
SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
97739824
SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
97749825
SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
97759826
SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3*,Token*,const Token*);
97769827
SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
@@ -10027,10 +10078,12 @@
1002710078
SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
1002810079
SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
1002910080
SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
1003010081
SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
1003110082
SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10083
+SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
10084
+
1003210085
1003310086
1003410087
/*
1003510088
** Available fault injectors. Should be numbered beginning with 0.
1003610089
*/
@@ -10449,11 +10502,11 @@
1044910502
**
1045010503
** There is only one exported symbol in this file - the function
1045110504
** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
1045210505
** All other code has file scope.
1045310506
**
10454
-** $Id: date.c,v 1.105 2009/04/03 12:04:37 drh Exp $
10507
+** $Id: date.c,v 1.107 2009/05/03 20:23:53 drh Exp $
1045510508
**
1045610509
** SQLite processes all times and dates as Julian Day numbers. The
1045710510
** dates and times are stored as the number of days since noon
1045810511
** in Greenwich on November 24, 4714 B.C. according to the Gregorian
1045910512
** calendar system.
@@ -10774,18 +10827,19 @@
1077410827
static int parseDateOrTime(
1077510828
sqlite3_context *context,
1077610829
const char *zDate,
1077710830
DateTime *p
1077810831
){
10832
+ int isRealNum; /* Return from sqlite3IsNumber(). Not used */
1077910833
if( parseYyyyMmDd(zDate,p)==0 ){
1078010834
return 0;
1078110835
}else if( parseHhMmSs(zDate, p)==0 ){
1078210836
return 0;
1078310837
}else if( sqlite3StrICmp(zDate,"now")==0){
1078410838
setDateTimeToCurrent(context, p);
1078510839
return 0;
10786
- }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
10840
+ }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
1078710841
double r;
1078810842
getValue(zDate, &r);
1078910843
p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
1079010844
p->validJD = 1;
1079110845
return 0;
@@ -10979,11 +11033,11 @@
1097911033
**
1098011034
** Treat the current value of p->iJD as the number of
1098111035
** seconds since 1970. Convert to a real julian day number.
1098211036
*/
1098311037
if( strcmp(z, "unixepoch")==0 && p->validJD ){
10984
- p->iJD = p->iJD/86400 + 21086676*(i64)10000000;
11038
+ p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
1098511039
clearYMD_HMS_TZ(p);
1098611040
rc = 0;
1098711041
}
1098811042
#ifndef SQLITE_OMIT_LOCALTIME
1098911043
else if( strcmp(z, "utc")==0 ){
@@ -14965,11 +15019,11 @@
1496515019
**
1496615020
*************************************************************************
1496715021
**
1496815022
** Memory allocation functions used throughout sqlite.
1496915023
**
14970
-** $Id: malloc.c,v 1.61 2009/03/24 15:08:10 drh Exp $
15024
+** $Id: malloc.c,v 1.62 2009/05/03 20:23:54 drh Exp $
1497115025
*/
1497215026
1497315027
/*
1497415028
** This routine runs when the memory allocator sees that the
1497515029
** total memory allocation is about to exceed the soft heap
@@ -15602,11 +15656,11 @@
1560215656
char *zNew;
1560315657
size_t n;
1560415658
if( z==0 ){
1560515659
return 0;
1560615660
}
15607
- n = (db ? sqlite3Strlen(db, z) : sqlite3Strlen30(z))+1;
15661
+ n = sqlite3Strlen30(z) + 1;
1560815662
assert( (n&0x7fffffff)==n );
1560915663
zNew = sqlite3DbMallocRaw(db, (int)n);
1561015664
if( zNew ){
1561115665
memcpy(zNew, z, n);
1561215666
}
@@ -15677,11 +15731,11 @@
1567715731
** the public domain. The original comments are included here for
1567815732
** completeness. They are very out-of-date but might be useful as
1567915733
** an historical reference. Most of the "enhancements" have been backed
1568015734
** out so that the functionality is now the same as standard printf().
1568115735
**
15682
-** $Id: printf.c,v 1.102 2009/04/08 16:10:04 drh Exp $
15736
+** $Id: printf.c,v 1.103 2009/05/04 20:20:16 drh Exp $
1568315737
**
1568415738
**************************************************************************
1568515739
**
1568615740
** The following modules is an enhanced replacement for the "printf" subroutines
1568715741
** found in the standard C library. The following enhancements are
@@ -16062,13 +16116,17 @@
1606216116
/* Fall through into the next case */
1606316117
case etORDINAL:
1606416118
case etRADIX:
1606516119
if( infop->flags & FLAG_SIGNED ){
1606616120
i64 v;
16067
- if( flag_longlong ) v = va_arg(ap,i64);
16068
- else if( flag_long ) v = va_arg(ap,long int);
16069
- else v = va_arg(ap,int);
16121
+ if( flag_longlong ){
16122
+ v = va_arg(ap,i64);
16123
+ }else if( flag_long ){
16124
+ v = va_arg(ap,long int);
16125
+ }else{
16126
+ v = va_arg(ap,int);
16127
+ }
1607016128
if( v<0 ){
1607116129
longvalue = -v;
1607216130
prefix = '-';
1607316131
}else{
1607416132
longvalue = v;
@@ -16075,13 +16133,17 @@
1607516133
if( flag_plussign ) prefix = '+';
1607616134
else if( flag_blanksign ) prefix = ' ';
1607716135
else prefix = 0;
1607816136
}
1607916137
}else{
16080
- if( flag_longlong ) longvalue = va_arg(ap,u64);
16081
- else if( flag_long ) longvalue = va_arg(ap,unsigned long int);
16082
- else longvalue = va_arg(ap,unsigned int);
16138
+ if( flag_longlong ){
16139
+ longvalue = va_arg(ap,u64);
16140
+ }else if( flag_long ){
16141
+ longvalue = va_arg(ap,unsigned long int);
16142
+ }else{
16143
+ longvalue = va_arg(ap,unsigned int);
16144
+ }
1608316145
prefix = 0;
1608416146
}
1608516147
if( longvalue==0 ) flag_alternateform = 0;
1608616148
if( flag_zeropad && precision<width-(prefix!=0) ){
1608716149
precision = width-(prefix!=0);
@@ -16824,11 +16886,11 @@
1682416886
** VDBE. This information used to all be at the top of the single
1682516887
** source code file "vdbe.c". When that file became too big (over
1682616888
** 6000 lines long) it was split up into several smaller files and
1682716889
** this header information was factored out.
1682816890
**
16829
-** $Id: vdbeInt.h,v 1.167 2009/04/10 12:55:17 danielk1977 Exp $
16891
+** $Id: vdbeInt.h,v 1.170 2009/05/04 11:42:30 danielk1977 Exp $
1683016892
*/
1683116893
#ifndef _VDBEINT_H_
1683216894
#define _VDBEINT_H_
1683316895
1683416896
/*
@@ -16888,10 +16950,14 @@
1688816950
KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
1688916951
int nField; /* Number of fields in the header */
1689016952
i64 seqCount; /* Sequence counter */
1689116953
sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
1689216954
const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
16955
+
16956
+ /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
16957
+ ** OP_IsUnique opcode on this cursor. */
16958
+ int seekResult;
1689316959
1689416960
/* Cached information about the header for the data record that the
1689516961
** cursor is currently pointing to. Only valid if cacheValid is true.
1689616962
** aRow might point to (ephemeral) data for the current row, or it might
1689716963
** be NULL.
@@ -17732,12 +17798,15 @@
1773217798
** Utility functions used throughout sqlite.
1773317799
**
1773417800
** This file contains functions for allocating memory, comparing
1773517801
** strings, and stuff like that.
1773617802
**
17737
-** $Id: util.c,v 1.249 2009/03/01 22:29:20 drh Exp $
17803
+** $Id: util.c,v 1.254 2009/05/06 19:03:14 drh Exp $
1773817804
*/
17805
+#ifdef SQLITE_HAVE_ISNAN
17806
+# include <math.h>
17807
+#endif
1773917808
1774017809
/*
1774117810
** Routine needed to support the testcase() macro.
1774217811
*/
1774317812
#ifdef SQLITE_COVERAGE_TEST
@@ -17768,13 +17837,24 @@
1776817837
}
1776917838
#endif
1777017839
1777117840
/*
1777217841
** Return true if the floating point value is Not a Number (NaN).
17842
+**
17843
+** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
17844
+** Otherwise, we have our own implementation that works on most systems.
1777317845
*/
1777417846
SQLITE_PRIVATE int sqlite3IsNaN(double x){
17775
- /* This NaN test sometimes fails if compiled on GCC with -ffast-math.
17847
+ int rc; /* The value return */
17848
+#if !defined(SQLITE_HAVE_ISNAN)
17849
+ /*
17850
+ ** Systems that support the isnan() library function should probably
17851
+ ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
17852
+ ** found that many systems do not have a working isnan() function so
17853
+ ** this implementation is provided as an alternative.
17854
+ **
17855
+ ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
1777617856
** On the other hand, the use of -ffast-math comes with the following
1777717857
** warning:
1777817858
**
1777917859
** This option [-ffast-math] should never be turned on by any
1778017860
** -O option since it can result in incorrect output for programs
@@ -17792,41 +17872,32 @@
1779217872
#ifdef __FAST_MATH__
1779317873
# error SQLite will not work correctly with the -ffast-math option of GCC.
1779417874
#endif
1779517875
volatile double y = x;
1779617876
volatile double z = y;
17797
- return y!=z;
17877
+ rc = (y!=z);
17878
+#else /* if defined(SQLITE_HAVE_ISNAN) */
17879
+ rc = isnan(x);
17880
+#endif /* SQLITE_HAVE_ISNAN */
17881
+ testcase( rc );
17882
+ return rc;
1779817883
}
1779917884
1780017885
/*
1780117886
** Compute a string length that is limited to what can be stored in
1780217887
** lower 30 bits of a 32-bit signed integer.
17888
+**
17889
+** The value returned will never be negative. Nor will it ever be greater
17890
+** than the actual length of the string. For very long strings (greater
17891
+** than 1GiB) the value returned might be less than the true string length.
1780317892
*/
1780417893
SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
1780517894
const char *z2 = z;
1780617895
while( *z2 ){ z2++; }
1780717896
return 0x3fffffff & (int)(z2 - z);
1780817897
}
1780917898
17810
-/*
17811
-** Return the length of a string, except do not allow the string length
17812
-** to exceed the SQLITE_LIMIT_LENGTH setting.
17813
-*/
17814
-SQLITE_PRIVATE int sqlite3Strlen(sqlite3 *db, const char *z){
17815
- const char *z2 = z;
17816
- int len;
17817
- int x;
17818
- while( *z2 ){ z2++; }
17819
- x = (int)(z2 - z);
17820
- len = 0x7fffffff & x;
17821
- if( len!=x || len > db->aLimit[SQLITE_LIMIT_LENGTH] ){
17822
- return db->aLimit[SQLITE_LIMIT_LENGTH];
17823
- }else{
17824
- return len;
17825
- }
17826
-}
17827
-
1782817899
/*
1782917900
** Set the most recent error code and error string for the sqlite
1783017901
** handle "db". The error code is set to "err_code".
1783117902
**
1783217903
** If it is not NULL, string zFormat specifies the format of the
@@ -17881,10 +17952,11 @@
1788117952
*/
1788217953
SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
1788317954
va_list ap;
1788417955
sqlite3 *db = pParse->db;
1788517956
pParse->nErr++;
17957
+ testcase( pParse->zErrMsg!=0 );
1788617958
sqlite3DbFree(db, pParse->zErrMsg);
1788717959
va_start(ap, zFormat);
1788817960
pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap);
1788917961
va_end(ap);
1789017962
if( pParse->rc==SQLITE_OK ){
@@ -17904,40 +17976,48 @@
1790417976
/*
1790517977
** Convert an SQL-style quoted string into a normal string by removing
1790617978
** the quote characters. The conversion is done in-place. If the
1790717979
** input does not begin with a quote character, then this routine
1790817980
** is a no-op.
17981
+**
17982
+** The input string must be zero-terminated. A new zero-terminator
17983
+** is added to the dequoted string.
17984
+**
17985
+** The return value is -1 if no dequoting occurs or the length of the
17986
+** dequoted string, exclusive of the zero terminator, if dequoting does
17987
+** occur.
1790917988
**
1791017989
** 2002-Feb-14: This routine is extended to remove MS-Access style
1791117990
** brackets from around identifers. For example: "[a-b-c]" becomes
1791217991
** "a-b-c".
1791317992
*/
17914
-SQLITE_PRIVATE void sqlite3Dequote(char *z){
17993
+SQLITE_PRIVATE int sqlite3Dequote(char *z){
1791517994
char quote;
1791617995
int i, j;
17917
- if( z==0 ) return;
17996
+ if( z==0 ) return -1;
1791817997
quote = z[0];
1791917998
switch( quote ){
1792017999
case '\'': break;
1792118000
case '"': break;
1792218001
case '`': break; /* For MySQL compatibility */
1792318002
case '[': quote = ']'; break; /* For MS SqlServer compatibility */
17924
- default: return;
18003
+ default: return -1;
1792518004
}
17926
- for(i=1, j=0; z[i]; i++){
18005
+ for(i=1, j=0; ALWAYS(z[i]); i++){
1792718006
if( z[i]==quote ){
1792818007
if( z[i+1]==quote ){
1792918008
z[j++] = quote;
1793018009
i++;
1793118010
}else{
17932
- z[j++] = 0;
1793318011
break;
1793418012
}
1793518013
}else{
1793618014
z[j++] = z[i];
1793718015
}
1793818016
}
18017
+ z[j] = 0;
18018
+ return j;
1793918019
}
1794018020
1794118021
/* Convenient short-hand */
1794218022
#define UpperToLower sqlite3UpperToLower
1794318023
@@ -17959,14 +18039,19 @@
1795918039
while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
1796018040
return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
1796118041
}
1796218042
1796318043
/*
17964
-** Return TRUE if z is a pure numeric string. Return FALSE if the
17965
-** string contains any character which is not part of a number. If
17966
-** the string is numeric and contains the '.' character, set *realnum
17967
-** to TRUE (otherwise FALSE).
18044
+** Return TRUE if z is a pure numeric string. Return FALSE and leave
18045
+** *realnum unchanged if the string contains any character which is not
18046
+** part of a number.
18047
+**
18048
+** If the string is pure numeric, set *realnum to TRUE if the string
18049
+** contains the '.' character or an "E+000" style exponentiation suffix.
18050
+** Otherwise set *realnum to FALSE. Note that just becaue *realnum is
18051
+** false does not mean that the number can be successfully converted into
18052
+** an integer - it might be too big.
1796818053
**
1796918054
** An empty string is considered non-numeric.
1797018055
*/
1797118056
SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
1797218057
int incr = (enc==SQLITE_UTF8?1:2);
@@ -17974,24 +18059,24 @@
1797418059
if( *z=='-' || *z=='+' ) z += incr;
1797518060
if( !sqlite3Isdigit(*z) ){
1797618061
return 0;
1797718062
}
1797818063
z += incr;
17979
- if( realnum ) *realnum = 0;
18064
+ *realnum = 0;
1798018065
while( sqlite3Isdigit(*z) ){ z += incr; }
1798118066
if( *z=='.' ){
1798218067
z += incr;
1798318068
if( !sqlite3Isdigit(*z) ) return 0;
1798418069
while( sqlite3Isdigit(*z) ){ z += incr; }
17985
- if( realnum ) *realnum = 1;
18070
+ *realnum = 1;
1798618071
}
1798718072
if( *z=='e' || *z=='E' ){
1798818073
z += incr;
1798918074
if( *z=='+' || *z=='-' ) z += incr;
1799018075
if( !sqlite3Isdigit(*z) ) return 0;
1799118076
while( sqlite3Isdigit(*z) ){ z += incr; }
17992
- if( realnum ) *realnum = 1;
18077
+ *realnum = 1;
1799318078
}
1799418079
return *z==0;
1799518080
}
1799618081
1799718082
/*
@@ -18146,29 +18231,29 @@
1814618231
return compare2pow63(zNum)<neg;
1814718232
}
1814818233
}
1814918234
1815018235
/*
18151
-** The string zNum represents an integer. There might be some other
18236
+** The string zNum represents an unsigned integer. There might be some other
1815218237
** information following the integer too, but that part is ignored.
1815318238
** If the integer that the prefix of zNum represents will fit in a
1815418239
** 64-bit signed integer, return TRUE. Otherwise return FALSE.
1815518240
**
18156
-** This routine returns FALSE for the string -9223372036854775808 even that
18157
-** that number will, in theory fit in a 64-bit integer. Positive
18158
-** 9223373036854775808 will not fit in 64 bits. So it seems safer to return
18159
-** false.
18241
+** If the negFlag parameter is true, that means that zNum really represents
18242
+** a negative number. (The leading "-" is omitted from zNum.) This
18243
+** parameter is needed to determine a boundary case. A string
18244
+** of "9223373036854775808" returns false if negFlag is false or true
18245
+** if negFlag is true.
18246
+**
18247
+** Leading zeros are ignored.
1816018248
*/
1816118249
SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
1816218250
int i, c;
1816318251
int neg = 0;
18164
- if( *zNum=='-' ){
18165
- neg = 1;
18166
- zNum++;
18167
- }else if( *zNum=='+' ){
18168
- zNum++;
18169
- }
18252
+
18253
+ assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */
18254
+
1817018255
if( negFlag ) neg = 1-neg;
1817118256
while( *zNum=='0' ){
1817218257
zNum++; /* Skip leading zeros. Ticket #2454 */
1817318258
}
1817418259
for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
@@ -18469,50 +18554,84 @@
1846918554
** this function assumes the single-byte case has already been handled.
1847018555
*/
1847118556
SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
1847218557
u32 a,b;
1847318558
18559
+ /* The 1-byte case. Overwhelmingly the most common. Handled inline
18560
+ ** by the getVarin32() macro */
1847418561
a = *p;
1847518562
/* a: p0 (unmasked) */
1847618563
#ifndef getVarint32
1847718564
if (!(a&0x80))
1847818565
{
18566
+ /* Values between 0 and 127 */
1847918567
*v = a;
1848018568
return 1;
1848118569
}
1848218570
#endif
1848318571
18572
+ /* The 2-byte case */
1848418573
p++;
1848518574
b = *p;
1848618575
/* b: p1 (unmasked) */
1848718576
if (!(b&0x80))
1848818577
{
18578
+ /* Values between 128 and 16383 */
1848918579
a &= 0x7f;
1849018580
a = a<<7;
1849118581
*v = a | b;
1849218582
return 2;
1849318583
}
1849418584
18585
+ /* The 3-byte case */
1849518586
p++;
1849618587
a = a<<14;
1849718588
a |= *p;
1849818589
/* a: p0<<14 | p2 (unmasked) */
1849918590
if (!(a&0x80))
1850018591
{
18592
+ /* Values between 16384 and 2097151 */
1850118593
a &= (0x7f<<14)|(0x7f);
1850218594
b &= 0x7f;
1850318595
b = b<<7;
1850418596
*v = a | b;
1850518597
return 3;
1850618598
}
1850718599
18600
+ /* A 32-bit varint is used to store size information in btrees.
18601
+ ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
18602
+ ** A 3-byte varint is sufficient, for example, to record the size
18603
+ ** of a 1048569-byte BLOB or string.
18604
+ **
18605
+ ** We only unroll the first 1-, 2-, and 3- byte cases. The very
18606
+ ** rare larger cases can be handled by the slower 64-bit varint
18607
+ ** routine.
18608
+ */
18609
+#if 1
18610
+ {
18611
+ u64 v64;
18612
+ u8 n;
18613
+
18614
+ p -= 2;
18615
+ n = sqlite3GetVarint(p, &v64);
18616
+ assert( n>3 && n<=9 );
18617
+ *v = (u32)v64;
18618
+ return n;
18619
+ }
18620
+
18621
+#else
18622
+ /* For following code (kept for historical record only) shows an
18623
+ ** unrolling for the 3- and 4-byte varint cases. This code is
18624
+ ** slightly faster, but it is also larger and much harder to test.
18625
+ */
1850818626
p++;
1850918627
b = b<<14;
1851018628
b |= *p;
1851118629
/* b: p1<<14 | p3 (unmasked) */
1851218630
if (!(b&0x80))
1851318631
{
18632
+ /* Values between 2097152 and 268435455 */
1851418633
b &= (0x7f<<14)|(0x7f);
1851518634
a &= (0x7f<<14)|(0x7f);
1851618635
a = a<<7;
1851718636
*v = a | b;
1851818637
return 4;
@@ -18522,10 +18641,11 @@
1852218641
a = a<<14;
1852318642
a |= *p;
1852418643
/* a: p0<<28 | p2<<14 | p4 (unmasked) */
1852518644
if (!(a&0x80))
1852618645
{
18646
+ /* Walues between 268435456 and 34359738367 */
1852718647
a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
1852818648
b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
1852918649
b = b<<7;
1853018650
*v = a | b;
1853118651
return 5;
@@ -18543,10 +18663,11 @@
1854318663
n = sqlite3GetVarint(p, &v64);
1854418664
assert( n>5 && n<=9 );
1854518665
*v = (u32)v64;
1854618666
return n;
1854718667
}
18668
+#endif
1854818669
}
1854918670
1855018671
/*
1855118672
** Return the number of bytes that will be needed to store the given
1855218673
** 64-bit integer.
@@ -18554,11 +18675,11 @@
1855418675
SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
1855518676
int i = 0;
1855618677
do{
1855718678
i++;
1855818679
v >>= 7;
18559
- }while( v!=0 && i<9 );
18680
+ }while( v!=0 && ALWAYS(i<9) );
1856018681
return i;
1856118682
}
1856218683
1856318684
1856418685
/*
@@ -18692,17 +18813,22 @@
1869218813
*/
1869318814
SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
1869418815
u32 magic;
1869518816
if( db==0 ) return 0;
1869618817
magic = db->magic;
18697
- if( magic!=SQLITE_MAGIC_OPEN &&
18698
- magic!=SQLITE_MAGIC_BUSY ) return 0;
18699
- return 1;
18818
+ if( magic!=SQLITE_MAGIC_OPEN
18819
+#ifdef SQLITE_DEBUG
18820
+ && magic!=SQLITE_MAGIC_BUSY
18821
+#endif
18822
+ ){
18823
+ return 0;
18824
+ }else{
18825
+ return 1;
18826
+ }
1870018827
}
1870118828
SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
1870218829
u32 magic;
18703
- if( db==0 ) return 0;
1870418830
magic = db->magic;
1870518831
if( magic!=SQLITE_MAGIC_SICK &&
1870618832
magic!=SQLITE_MAGIC_OPEN &&
1870718833
magic!=SQLITE_MAGIC_BUSY ) return 0;
1870818834
return 1;
@@ -18722,23 +18848,20 @@
1872218848
**
1872318849
*************************************************************************
1872418850
** This is the implementation of generic hash-tables
1872518851
** used in SQLite.
1872618852
**
18727
-** $Id: hash.c,v 1.33 2009/01/09 01:12:28 drh Exp $
18853
+** $Id: hash.c,v 1.37 2009/05/02 13:29:38 drh Exp $
1872818854
*/
1872918855
1873018856
/* Turn bulk memory into a hash table object by initializing the
1873118857
** fields of the Hash structure.
1873218858
**
1873318859
** "pNew" is a pointer to the hash table that is to be initialized.
18734
-** "copyKey" is true if the hash table should make its own private
18735
-** copy of keys and false if it should just use the supplied pointer.
1873618860
*/
18737
-SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew, int copyKey){
18861
+SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
1873818862
assert( pNew!=0 );
18739
- pNew->copyKey = copyKey!=0;
1874018863
pNew->first = 0;
1874118864
pNew->count = 0;
1874218865
pNew->htsize = 0;
1874318866
pNew->ht = 0;
1874418867
}
@@ -18756,47 +18879,46 @@
1875618879
sqlite3_free(pH->ht);
1875718880
pH->ht = 0;
1875818881
pH->htsize = 0;
1875918882
while( elem ){
1876018883
HashElem *next_elem = elem->next;
18761
- if( pH->copyKey ){
18762
- sqlite3_free(elem->pKey);
18763
- }
1876418884
sqlite3_free(elem);
1876518885
elem = next_elem;
1876618886
}
1876718887
pH->count = 0;
1876818888
}
1876918889
1877018890
/*
18771
-** Hash and comparison functions when the mode is SQLITE_HASH_STRING
18891
+** The hashing function.
1877218892
*/
18773
-static int strHash(const void *pKey, int nKey){
18774
- const char *z = (const char *)pKey;
18893
+static unsigned int strHash(const char *z, int nKey){
1877518894
int h = 0;
18776
- if( nKey<=0 ) nKey = sqlite3Strlen30(z);
18895
+ assert( nKey>=0 );
1877718896
while( nKey > 0 ){
1877818897
h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
1877918898
nKey--;
1878018899
}
18781
- return h & 0x7fffffff;
18782
-}
18783
-static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
18784
- if( n1!=n2 ) return 1;
18785
- return sqlite3StrNICmp((const char*)pKey1,(const char*)pKey2,n1);
18900
+ return h;
1878618901
}
1878718902
1878818903
18789
-/* Link an element into the hash table
18904
+/* Link pNew element into the hash table pH. If pEntry!=0 then also
18905
+** insert pNew into the pEntry hash bucket.
1879018906
*/
1879118907
static void insertElement(
1879218908
Hash *pH, /* The complete hash table */
1879318909
struct _ht *pEntry, /* The entry into which pNew is inserted */
1879418910
HashElem *pNew /* The element to be inserted */
1879518911
){
1879618912
HashElem *pHead; /* First element already in pEntry */
18797
- pHead = pEntry->chain;
18913
+ if( pEntry ){
18914
+ pHead = pEntry->count ? pEntry->chain : 0;
18915
+ pEntry->count++;
18916
+ pEntry->chain = pNew;
18917
+ }else{
18918
+ pHead = 0;
18919
+ }
1879818920
if( pHead ){
1879918921
pNew->next = pHead;
1880018922
pNew->prev = pHead->prev;
1880118923
if( pHead->prev ){ pHead->prev->next = pNew; }
1880218924
else { pH->first = pNew; }
@@ -18805,73 +18927,77 @@
1880518927
pNew->next = pH->first;
1880618928
if( pH->first ){ pH->first->prev = pNew; }
1880718929
pNew->prev = 0;
1880818930
pH->first = pNew;
1880918931
}
18810
- pEntry->count++;
18811
- pEntry->chain = pNew;
1881218932
}
1881318933
1881418934
1881518935
/* Resize the hash table so that it cantains "new_size" buckets.
18816
-** "new_size" must be a power of 2. The hash table might fail
18817
-** to resize if sqlite3_malloc() fails.
18936
+**
18937
+** The hash table might fail to resize if sqlite3_malloc() fails or
18938
+** if the new size is the same as the prior size.
18939
+** Return TRUE if the resize occurs and false if not.
1881818940
*/
18819
-static void rehash(Hash *pH, int new_size){
18941
+static int rehash(Hash *pH, unsigned int new_size){
1882018942
struct _ht *new_ht; /* The new hash table */
1882118943
HashElem *elem, *next_elem; /* For looping over existing elements */
1882218944
18823
-#ifdef SQLITE_MALLOC_SOFT_LIMIT
18945
+#if SQLITE_MALLOC_SOFT_LIMIT>0
1882418946
if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
1882518947
new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
1882618948
}
18827
- if( new_size==pH->htsize ) return;
18949
+ if( new_size==pH->htsize ) return 0;
1882818950
#endif
1882918951
18830
- /* There is a call to sqlite3_malloc() inside rehash(). If there is
18831
- ** already an allocation at pH->ht, then if this malloc() fails it
18832
- ** is benign (since failing to resize a hash table is a performance
18833
- ** hit only, not a fatal error).
18952
+ /* The inability to allocates space for a larger hash table is
18953
+ ** a performance hit but it is not a fatal error. So mark the
18954
+ ** allocation as a benign.
1883418955
*/
18835
- if( pH->htsize>0 ) sqlite3BeginBenignMalloc();
18836
- new_ht = (struct _ht *)sqlite3MallocZero( new_size*sizeof(struct _ht) );
18837
- if( pH->htsize>0 ) sqlite3EndBenignMalloc();
18956
+ sqlite3BeginBenignMalloc();
18957
+ new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
18958
+ sqlite3EndBenignMalloc();
1883818959
18839
- if( new_ht==0 ) return;
18960
+ if( new_ht==0 ) return 0;
1884018961
sqlite3_free(pH->ht);
1884118962
pH->ht = new_ht;
18842
- pH->htsize = new_size;
18963
+ pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
18964
+ memset(new_ht, 0, new_size*sizeof(struct _ht));
1884318965
for(elem=pH->first, pH->first=0; elem; elem = next_elem){
18844
- int h = strHash(elem->pKey, elem->nKey) & (new_size-1);
18966
+ unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
1884518967
next_elem = elem->next;
1884618968
insertElement(pH, &new_ht[h], elem);
1884718969
}
18970
+ return 1;
1884818971
}
1884918972
1885018973
/* This function (for internal use only) locates an element in an
1885118974
** hash table that matches the given key. The hash for this key has
1885218975
** already been computed and is passed as the 4th parameter.
1885318976
*/
1885418977
static HashElem *findElementGivenHash(
1885518978
const Hash *pH, /* The pH to be searched */
18856
- const void *pKey, /* The key we are searching for */
18857
- int nKey,
18858
- int h /* The hash for this key. */
18979
+ const char *pKey, /* The key we are searching for */
18980
+ int nKey, /* Bytes in key (not counting zero terminator) */
18981
+ unsigned int h /* The hash for this key. */
1885918982
){
1886018983
HashElem *elem; /* Used to loop thru the element list */
1886118984
int count; /* Number of elements left to test */
1886218985
1886318986
if( pH->ht ){
1886418987
struct _ht *pEntry = &pH->ht[h];
1886518988
elem = pEntry->chain;
1886618989
count = pEntry->count;
18867
- while( count-- && elem ){
18868
- if( strCompare(elem->pKey,elem->nKey,pKey,nKey)==0 ){
18869
- return elem;
18870
- }
18871
- elem = elem->next;
18990
+ }else{
18991
+ elem = pH->first;
18992
+ count = pH->count;
18993
+ }
18994
+ while( count-- && ALWAYS(elem) ){
18995
+ if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
18996
+ return elem;
1887218997
}
18998
+ elem = elem->next;
1887318999
}
1887419000
return 0;
1887519001
}
1887619002
1887719003
/* Remove a single entry from the hash table given a pointer to that
@@ -18878,11 +19004,11 @@
1887819004
** element and a hash on the element's key.
1887919005
*/
1888019006
static void removeElementGivenHash(
1888119007
Hash *pH, /* The pH containing "elem" */
1888219008
HashElem* elem, /* The element to be removed from the pH */
18883
- int h /* Hash value for the element */
19009
+ unsigned int h /* Hash value for the element */
1888419010
){
1888519011
struct _ht *pEntry;
1888619012
if( elem->prev ){
1888719013
elem->prev->next = elem->next;
1888819014
}else{
@@ -18889,20 +19015,17 @@
1888919015
pH->first = elem->next;
1889019016
}
1889119017
if( elem->next ){
1889219018
elem->next->prev = elem->prev;
1889319019
}
18894
- pEntry = &pH->ht[h];
18895
- if( pEntry->chain==elem ){
18896
- pEntry->chain = elem->next;
18897
- }
18898
- pEntry->count--;
18899
- if( pEntry->count<=0 ){
18900
- pEntry->chain = 0;
18901
- }
18902
- if( pH->copyKey ){
18903
- sqlite3_free(elem->pKey);
19020
+ if( pH->ht ){
19021
+ pEntry = &pH->ht[h];
19022
+ if( pEntry->chain==elem ){
19023
+ pEntry->chain = elem->next;
19024
+ }
19025
+ pEntry->count--;
19026
+ assert( pEntry->count>=0 );
1890419027
}
1890519028
sqlite3_free( elem );
1890619029
pH->count--;
1890719030
if( pH->count<=0 ){
1890819031
assert( pH->first==0 );
@@ -18909,108 +19032,86 @@
1890919032
assert( pH->count==0 );
1891019033
sqlite3HashClear(pH);
1891119034
}
1891219035
}
1891319036
18914
-/* Attempt to locate an element of the hash table pH with a key
18915
-** that matches pKey,nKey. Return a pointer to the corresponding
18916
-** HashElem structure for this element if it is found, or NULL
18917
-** otherwise.
18918
-*/
18919
-SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash *pH, const void *pKey, int nKey){
18920
- int h; /* A hash on key */
18921
- HashElem *elem; /* The element that matches key */
18922
-
18923
- if( pH==0 || pH->ht==0 ) return 0;
18924
- h = strHash(pKey,nKey);
18925
- elem = findElementGivenHash(pH,pKey,nKey, h % pH->htsize);
18926
- return elem;
18927
-}
18928
-
1892919037
/* Attempt to locate an element of the hash table pH with a key
1893019038
** that matches pKey,nKey. Return the data for this element if it is
1893119039
** found, or NULL if there is no match.
1893219040
*/
18933
-SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
19041
+SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
1893419042
HashElem *elem; /* The element that matches key */
18935
- elem = sqlite3HashFindElem(pH, pKey, nKey);
19043
+ unsigned int h; /* A hash on key */
19044
+
19045
+ assert( pH!=0 );
19046
+ assert( pKey!=0 );
19047
+ assert( nKey>=0 );
19048
+ if( pH->ht ){
19049
+ h = strHash(pKey, nKey) % pH->htsize;
19050
+ }else{
19051
+ h = 0;
19052
+ }
19053
+ elem = findElementGivenHash(pH, pKey, nKey, h);
1893619054
return elem ? elem->data : 0;
1893719055
}
1893819056
1893919057
/* Insert an element into the hash table pH. The key is pKey,nKey
1894019058
** and the data is "data".
1894119059
**
1894219060
** If no element exists with a matching key, then a new
18943
-** element is created. A copy of the key is made if the copyKey
18944
-** flag is set. NULL is returned.
19061
+** element is created and NULL is returned.
1894519062
**
1894619063
** If another element already exists with the same key, then the
1894719064
** new data replaces the old data and the old data is returned.
1894819065
** The key is not copied in this instance. If a malloc fails, then
1894919066
** the new data is returned and the hash table is unchanged.
1895019067
**
1895119068
** If the "data" parameter to this function is NULL, then the
1895219069
** element corresponding to "key" is removed from the hash table.
1895319070
*/
18954
-SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
18955
- int hraw; /* Raw hash value of the key */
18956
- int h; /* the hash of the key modulo hash table size */
19071
+SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
19072
+ unsigned int h; /* the hash of the key modulo hash table size */
1895719073
HashElem *elem; /* Used to loop thru the element list */
1895819074
HashElem *new_elem; /* New element added to the pH */
1895919075
1896019076
assert( pH!=0 );
18961
- hraw = strHash(pKey, nKey);
19077
+ assert( pKey!=0 );
19078
+ assert( nKey>=0 );
1896219079
if( pH->htsize ){
18963
- h = hraw % pH->htsize;
18964
- elem = findElementGivenHash(pH,pKey,nKey,h);
18965
- if( elem ){
18966
- void *old_data = elem->data;
18967
- if( data==0 ){
18968
- removeElementGivenHash(pH,elem,h);
18969
- }else{
18970
- elem->data = data;
18971
- if( !pH->copyKey ){
18972
- elem->pKey = (void *)pKey;
18973
- }
18974
- assert(nKey==elem->nKey);
18975
- }
18976
- return old_data;
18977
- }
19080
+ h = strHash(pKey, nKey) % pH->htsize;
19081
+ }else{
19082
+ h = 0;
19083
+ }
19084
+ elem = findElementGivenHash(pH,pKey,nKey,h);
19085
+ if( elem ){
19086
+ void *old_data = elem->data;
19087
+ if( data==0 ){
19088
+ removeElementGivenHash(pH,elem,h);
19089
+ }else{
19090
+ elem->data = data;
19091
+ elem->pKey = pKey;
19092
+ assert(nKey==elem->nKey);
19093
+ }
19094
+ return old_data;
1897819095
}
1897919096
if( data==0 ) return 0;
1898019097
new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
1898119098
if( new_elem==0 ) return data;
18982
- if( pH->copyKey && pKey!=0 ){
18983
- new_elem->pKey = sqlite3Malloc( nKey );
18984
- if( new_elem->pKey==0 ){
18985
- sqlite3_free(new_elem);
18986
- return data;
18987
- }
18988
- memcpy((void*)new_elem->pKey, pKey, nKey);
18989
- }else{
18990
- new_elem->pKey = (void*)pKey;
18991
- }
19099
+ new_elem->pKey = pKey;
1899219100
new_elem->nKey = nKey;
19101
+ new_elem->data = data;
1899319102
pH->count++;
18994
- if( pH->htsize==0 ){
18995
- rehash(pH, 128/sizeof(pH->ht[0]));
18996
- if( pH->htsize==0 ){
18997
- pH->count = 0;
18998
- if( pH->copyKey ){
18999
- sqlite3_free(new_elem->pKey);
19000
- }
19001
- sqlite3_free(new_elem);
19002
- return data;
19003
- }
19004
- }
19005
- if( pH->count > pH->htsize ){
19006
- rehash(pH,pH->htsize*2);
19007
- }
19008
- assert( pH->htsize>0 );
19009
- h = hraw % pH->htsize;
19010
- insertElement(pH, &pH->ht[h], new_elem);
19011
- new_elem->data = data;
19103
+ if( pH->count>=10 && pH->count > 2*pH->htsize ){
19104
+ if( rehash(pH, pH->count*2) && pH->htsize ){
19105
+ h = strHash(pKey, nKey) % pH->htsize;
19106
+ }
19107
+ }
19108
+ if( pH->ht ){
19109
+ insertElement(pH, &pH->ht[h], new_elem);
19110
+ }else{
19111
+ insertElement(pH, 0, new_elem);
19112
+ }
1901219113
return 0;
1901319114
}
1901419115
1901519116
/************** End of hash.c ************************************************/
1901619117
/************** Begin file opcodes.c *****************************************/
@@ -19028,78 +19129,78 @@
1902819129
/* 7 */ "Savepoint",
1902919130
/* 8 */ "RowKey",
1903019131
/* 9 */ "SCopy",
1903119132
/* 10 */ "OpenWrite",
1903219133
/* 11 */ "If",
19033
- /* 12 */ "VRowid",
19034
- /* 13 */ "CollSeq",
19035
- /* 14 */ "OpenRead",
19036
- /* 15 */ "Expire",
19037
- /* 16 */ "AutoCommit",
19038
- /* 17 */ "Pagecount",
19039
- /* 18 */ "IntegrityCk",
19134
+ /* 12 */ "CollSeq",
19135
+ /* 13 */ "OpenRead",
19136
+ /* 14 */ "Expire",
19137
+ /* 15 */ "AutoCommit",
19138
+ /* 16 */ "Pagecount",
19139
+ /* 17 */ "IntegrityCk",
19140
+ /* 18 */ "Sort",
1904019141
/* 19 */ "Not",
19041
- /* 20 */ "Sort",
19042
- /* 21 */ "Copy",
19043
- /* 22 */ "Trace",
19044
- /* 23 */ "Function",
19045
- /* 24 */ "IfNeg",
19046
- /* 25 */ "Noop",
19047
- /* 26 */ "Return",
19048
- /* 27 */ "NewRowid",
19049
- /* 28 */ "Variable",
19050
- /* 29 */ "String",
19051
- /* 30 */ "RealAffinity",
19052
- /* 31 */ "VRename",
19053
- /* 32 */ "ParseSchema",
19054
- /* 33 */ "VOpen",
19055
- /* 34 */ "Close",
19056
- /* 35 */ "CreateIndex",
19057
- /* 36 */ "IsUnique",
19058
- /* 37 */ "NotFound",
19059
- /* 38 */ "Int64",
19060
- /* 39 */ "MustBeInt",
19061
- /* 40 */ "Halt",
19062
- /* 41 */ "Rowid",
19063
- /* 42 */ "IdxLT",
19064
- /* 43 */ "AddImm",
19065
- /* 44 */ "Statement",
19066
- /* 45 */ "RowData",
19067
- /* 46 */ "MemMax",
19068
- /* 47 */ "NotExists",
19069
- /* 48 */ "Gosub",
19070
- /* 49 */ "Integer",
19071
- /* 50 */ "Prev",
19072
- /* 51 */ "RowSetRead",
19073
- /* 52 */ "RowSetAdd",
19074
- /* 53 */ "VColumn",
19075
- /* 54 */ "CreateTable",
19076
- /* 55 */ "Last",
19077
- /* 56 */ "SeekLe",
19078
- /* 57 */ "IncrVacuum",
19079
- /* 58 */ "IdxRowid",
19080
- /* 59 */ "ResetCount",
19081
- /* 60 */ "ContextPush",
19082
- /* 61 */ "Yield",
19083
- /* 62 */ "DropTrigger",
19084
- /* 63 */ "DropIndex",
19085
- /* 64 */ "IdxGE",
19086
- /* 65 */ "IdxDelete",
19142
+ /* 20 */ "Copy",
19143
+ /* 21 */ "Trace",
19144
+ /* 22 */ "Function",
19145
+ /* 23 */ "IfNeg",
19146
+ /* 24 */ "Noop",
19147
+ /* 25 */ "Return",
19148
+ /* 26 */ "NewRowid",
19149
+ /* 27 */ "Variable",
19150
+ /* 28 */ "String",
19151
+ /* 29 */ "RealAffinity",
19152
+ /* 30 */ "VRename",
19153
+ /* 31 */ "ParseSchema",
19154
+ /* 32 */ "VOpen",
19155
+ /* 33 */ "Close",
19156
+ /* 34 */ "CreateIndex",
19157
+ /* 35 */ "IsUnique",
19158
+ /* 36 */ "NotFound",
19159
+ /* 37 */ "Int64",
19160
+ /* 38 */ "MustBeInt",
19161
+ /* 39 */ "Halt",
19162
+ /* 40 */ "Rowid",
19163
+ /* 41 */ "IdxLT",
19164
+ /* 42 */ "AddImm",
19165
+ /* 43 */ "Statement",
19166
+ /* 44 */ "RowData",
19167
+ /* 45 */ "MemMax",
19168
+ /* 46 */ "NotExists",
19169
+ /* 47 */ "Gosub",
19170
+ /* 48 */ "Integer",
19171
+ /* 49 */ "Prev",
19172
+ /* 50 */ "RowSetRead",
19173
+ /* 51 */ "RowSetAdd",
19174
+ /* 52 */ "VColumn",
19175
+ /* 53 */ "CreateTable",
19176
+ /* 54 */ "Last",
19177
+ /* 55 */ "SeekLe",
19178
+ /* 56 */ "IncrVacuum",
19179
+ /* 57 */ "IdxRowid",
19180
+ /* 58 */ "ResetCount",
19181
+ /* 59 */ "ContextPush",
19182
+ /* 60 */ "Yield",
19183
+ /* 61 */ "DropTrigger",
19184
+ /* 62 */ "DropIndex",
19185
+ /* 63 */ "IdxGE",
19186
+ /* 64 */ "IdxDelete",
19187
+ /* 65 */ "Vacuum",
1908719188
/* 66 */ "Or",
1908819189
/* 67 */ "And",
19089
- /* 68 */ "Vacuum",
19090
- /* 69 */ "IfNot",
19091
- /* 70 */ "DropTable",
19190
+ /* 68 */ "IfNot",
19191
+ /* 69 */ "DropTable",
19192
+ /* 70 */ "SeekLt",
1909219193
/* 71 */ "IsNull",
1909319194
/* 72 */ "NotNull",
1909419195
/* 73 */ "Ne",
1909519196
/* 74 */ "Eq",
1909619197
/* 75 */ "Gt",
1909719198
/* 76 */ "Le",
1909819199
/* 77 */ "Lt",
1909919200
/* 78 */ "Ge",
19100
- /* 79 */ "SeekLt",
19201
+ /* 79 */ "MakeRecord",
1910119202
/* 80 */ "BitAnd",
1910219203
/* 81 */ "BitOr",
1910319204
/* 82 */ "ShiftLeft",
1910419205
/* 83 */ "ShiftRight",
1910519206
/* 84 */ "Add",
@@ -19106,34 +19207,34 @@
1910619207
/* 85 */ "Subtract",
1910719208
/* 86 */ "Multiply",
1910819209
/* 87 */ "Divide",
1910919210
/* 88 */ "Remainder",
1911019211
/* 89 */ "Concat",
19111
- /* 90 */ "MakeRecord",
19112
- /* 91 */ "ResultRow",
19113
- /* 92 */ "Delete",
19212
+ /* 90 */ "ResultRow",
19213
+ /* 91 */ "Delete",
19214
+ /* 92 */ "AggFinal",
1911419215
/* 93 */ "BitNot",
1911519216
/* 94 */ "String8",
19116
- /* 95 */ "AggFinal",
19117
- /* 96 */ "Compare",
19118
- /* 97 */ "Goto",
19119
- /* 98 */ "TableLock",
19120
- /* 99 */ "Clear",
19121
- /* 100 */ "VerifyCookie",
19122
- /* 101 */ "AggStep",
19123
- /* 102 */ "SetNumColumns",
19124
- /* 103 */ "Transaction",
19125
- /* 104 */ "VFilter",
19126
- /* 105 */ "VDestroy",
19127
- /* 106 */ "ContextPop",
19128
- /* 107 */ "Next",
19129
- /* 108 */ "Count",
19130
- /* 109 */ "IdxInsert",
19131
- /* 110 */ "SeekGe",
19132
- /* 111 */ "Insert",
19133
- /* 112 */ "Destroy",
19134
- /* 113 */ "ReadCookie",
19217
+ /* 95 */ "Compare",
19218
+ /* 96 */ "Goto",
19219
+ /* 97 */ "TableLock",
19220
+ /* 98 */ "Clear",
19221
+ /* 99 */ "VerifyCookie",
19222
+ /* 100 */ "AggStep",
19223
+ /* 101 */ "SetNumColumns",
19224
+ /* 102 */ "Transaction",
19225
+ /* 103 */ "VFilter",
19226
+ /* 104 */ "VDestroy",
19227
+ /* 105 */ "ContextPop",
19228
+ /* 106 */ "Next",
19229
+ /* 107 */ "Count",
19230
+ /* 108 */ "IdxInsert",
19231
+ /* 109 */ "SeekGe",
19232
+ /* 110 */ "Insert",
19233
+ /* 111 */ "Destroy",
19234
+ /* 112 */ "ReadCookie",
19235
+ /* 113 */ "RowSetTest",
1913519236
/* 114 */ "LoadAnalysis",
1913619237
/* 115 */ "Explain",
1913719238
/* 116 */ "HaltIfNull",
1913819239
/* 117 */ "OpenPseudo",
1913919240
/* 118 */ "OpenEphemeral",
@@ -25901,11 +26002,11 @@
2590126002
**
2590226003
******************************************************************************
2590326004
**
2590426005
** This file contains code that is specific to windows.
2590526006
**
25906
-** $Id: os_win.c,v 1.154 2009/04/09 14:27:07 chw Exp $
26007
+** $Id: os_win.c,v 1.156 2009/04/23 19:08:33 shane Exp $
2590726008
*/
2590826009
#if SQLITE_OS_WIN /* This file is used for windows only */
2590926010
2591026011
2591126012
/*
@@ -27422,20 +27523,27 @@
2742227523
if( flags & SQLITE_OPEN_READWRITE ){
2742327524
dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
2742427525
}else{
2742527526
dwDesiredAccess = GENERIC_READ;
2742627527
}
27427
- if( flags & SQLITE_OPEN_CREATE ){
27528
+ /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
27529
+ ** created. SQLite doesn't use it to indicate "exclusive access"
27530
+ ** as it is usually understood.
27531
+ */
27532
+ assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
27533
+ if( flags & SQLITE_OPEN_EXCLUSIVE ){
27534
+ /* Creates a new file, only if it does not already exist. */
27535
+ /* If the file exists, it fails. */
27536
+ dwCreationDisposition = CREATE_NEW;
27537
+ }else if( flags & SQLITE_OPEN_CREATE ){
27538
+ /* Open existing file, or create if it doesn't exist */
2742827539
dwCreationDisposition = OPEN_ALWAYS;
2742927540
}else{
27541
+ /* Opens a file, only if it exists. */
2743027542
dwCreationDisposition = OPEN_EXISTING;
2743127543
}
27432
- if( flags & SQLITE_OPEN_MAIN_DB ){
27433
- dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
27434
- }else{
27435
- dwShareMode = 0;
27436
- }
27544
+ dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
2743727545
if( flags & SQLITE_OPEN_DELETEONCLOSE ){
2743827546
#if SQLITE_OS_WINCE
2743927547
dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
2744027548
isTemp = 1;
2744127549
#else
@@ -27710,17 +27818,15 @@
2771027818
if( rc == SQLITE_OK )
2771127819
{
2771227820
void *zConverted = convertUtf8Filename(zFullpath);
2771327821
if( zConverted ){
2771427822
if( isNT() ){
27715
- int i;
2771627823
/* trim path to just drive reference */
2771727824
WCHAR *p = zConverted;
27718
- for(i=0;i<MAX_PATH;i++){
27719
- if( p[i] == '\\' ){
27720
- i++;
27721
- p[i] = '\0';
27825
+ for(;*p;p++){
27826
+ if( *p == '\\' ){
27827
+ *p = '\0';
2772227828
break;
2772327829
}
2772427830
}
2772527831
dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
2772627832
&dwDummy,
@@ -27727,17 +27833,15 @@
2772727833
&bytesPerSector,
2772827834
&dwDummy,
2772927835
&dwDummy);
2773027836
#if SQLITE_OS_WINCE==0
2773127837
}else{
27732
- int i;
2773327838
/* trim path to just drive reference */
2773427839
CHAR *p = (CHAR *)zConverted;
27735
- for(i=0;i<MAX_PATH;i++){
27736
- if( p[i] == '\\' ){
27737
- i++;
27738
- p[i] = '\0';
27840
+ for(;*p;p++){
27841
+ if( *p == '\\' ){
27842
+ *p = '\0';
2773927843
break;
2774027844
}
2774127845
}
2774227846
dwRet = GetDiskFreeSpaceA((CHAR*)zConverted,
2774327847
&dwDummy,
@@ -28987,11 +29091,11 @@
2898729091
** sqlite3_pcache interface). It also contains part of the implementation
2898829092
** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
2898929093
** If the default page cache implementation is overriden, then neither of
2899029094
** these two features are available.
2899129095
**
28992
-** @(#) $Id: pcache1.c,v 1.10 2009/03/23 04:33:33 danielk1977 Exp $
29096
+** @(#) $Id: pcache1.c,v 1.11 2009/04/14 18:44:39 aswift Exp $
2899329097
*/
2899429098
2899529099
2899629100
typedef struct PCache1 PCache1;
2899729101
typedef struct PgHdr1 PgHdr1;
@@ -29497,11 +29601,11 @@
2949729601
goto fetch_out;
2949829602
}
2949929603
2950029604
/* Step 4. Try to recycle a page buffer if appropriate. */
2950129605
if( pCache->bPurgeable && pcache1.pLruTail && (
29502
- pCache->nPage>=pCache->nMax-1 || pcache1.nCurrentPage>=pcache1.nMaxPage
29606
+ (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
2950329607
)){
2950429608
pPage = pcache1.pLruTail;
2950529609
pcache1RemoveFromHash(pPage);
2950629610
pcache1PinPage(pPage);
2950729611
if( pPage->pCache->szPage!=pCache->szPage ){
@@ -29735,50 +29839,92 @@
2973529839
** May you find forgiveness for yourself and forgive others.
2973629840
** May you share freely, never taking more than you give.
2973729841
**
2973829842
*************************************************************************
2973929843
**
29740
-** This module implements an object we call a "Row Set".
29741
-**
29742
-** The RowSet object is a bag of rowids. Rowids
29743
-** are inserted into the bag in an arbitrary order. Then they are
29744
-** pulled from the bag in sorted order. Rowids only appear in the
29745
-** bag once. If the same rowid is inserted multiple times, the
29746
-** second and subsequent inserts make no difference on the output.
29747
-**
29748
-** This implementation accumulates rowids in a linked list. For
29749
-** output, it first sorts the linked list (removing duplicates during
29750
-** the sort) then returns elements one by one by walking the list.
29751
-**
29752
-** Big chunks of rowid/next-ptr pairs are allocated at a time, to
29753
-** reduce the malloc overhead.
29754
-**
29755
-** $Id: rowset.c,v 1.4 2009/04/01 19:35:55 drh Exp $
29756
-*/
29844
+** This module implements an object we call a "RowSet".
29845
+**
29846
+** The RowSet object is a collection of rowids. Rowids
29847
+** are inserted into the RowSet in an arbitrary order. Inserts
29848
+** can be intermixed with tests to see if a given rowid has been
29849
+** previously inserted into the RowSet.
29850
+**
29851
+** After all inserts are finished, it is possible to extract the
29852
+** elements of the RowSet in sorted order. Once this extraction
29853
+** process has started, no new elements may be inserted.
29854
+**
29855
+** Hence, the primitive operations for a RowSet are:
29856
+**
29857
+** CREATE
29858
+** INSERT
29859
+** TEST
29860
+** SMALLEST
29861
+** DESTROY
29862
+**
29863
+** The CREATE and DESTROY primitives are the constructor and destructor,
29864
+** obviously. The INSERT primitive adds a new element to the RowSet.
29865
+** TEST checks to see if an element is already in the RowSet. SMALLEST
29866
+** extracts the least value from the RowSet.
29867
+**
29868
+** The INSERT primitive might allocate additional memory. Memory is
29869
+** allocated in chunks so most INSERTs do no allocation. There is an
29870
+** upper bound on the size of allocated memory. No memory is freed
29871
+** until DESTROY.
29872
+**
29873
+** The TEST primitive includes a "batch" number. The TEST primitive
29874
+** will only see elements that were inserted before the last change
29875
+** in the batch number. In other words, if an INSERT occurs between
29876
+** two TESTs where the TESTs have the same batch nubmer, then the
29877
+** value added by the INSERT will not be visible to the second TEST.
29878
+** The initial batch number is zero, so if the very first TEST contains
29879
+** a non-zero batch number, it will see all prior INSERTs.
29880
+**
29881
+** No INSERTs may occurs after a SMALLEST. An assertion will fail if
29882
+** that is attempted.
29883
+**
29884
+** The cost of an INSERT is roughly constant. (Sometime new memory
29885
+** has to be allocated on an INSERT.) The cost of a TEST with a new
29886
+** batch number is O(NlogN) where N is the number of elements in the RowSet.
29887
+** The cost of a TEST using the same batch number is O(logN). The cost
29888
+** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
29889
+** primitives are constant time. The cost of DESTROY is O(N).
29890
+**
29891
+** There is an added cost of O(N) when switching between TEST and
29892
+** SMALLEST primitives.
29893
+**
29894
+** $Id: rowset.c,v 1.6 2009/04/22 15:32:59 drh Exp $
29895
+*/
29896
+
29897
+
29898
+/*
29899
+** Target size for allocation chunks.
29900
+*/
29901
+#define ROWSET_ALLOCATION_SIZE 1024
2975729902
2975829903
/*
2975929904
** The number of rowset entries per allocation chunk.
2976029905
*/
29761
-#define ROWSET_ENTRY_PER_CHUNK 63
29906
+#define ROWSET_ENTRY_PER_CHUNK \
29907
+ ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
2976229908
2976329909
/*
29764
-** Each entry in a RowSet is an instance of the following
29765
-** structure:
29910
+** Each entry in a RowSet is an instance of the following object.
2976629911
*/
2976729912
struct RowSetEntry {
2976829913
i64 v; /* ROWID value for this entry */
29769
- struct RowSetEntry *pNext; /* Next entry on a list of all entries */
29914
+ struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
29915
+ struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
2977029916
};
2977129917
2977229918
/*
29773
-** Index entries are allocated in large chunks (instances of the
29919
+** RowSetEntry objects are allocated in large chunks (instances of the
2977429920
** following structure) to reduce memory allocation overhead. The
2977529921
** chunks are kept on a linked list so that they can be deallocated
2977629922
** when the RowSet is destroyed.
2977729923
*/
2977829924
struct RowSetChunk {
29779
- struct RowSetChunk *pNext; /* Next chunk on list of them all */
29925
+ struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
2978029926
struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
2978129927
};
2978229928
2978329929
/*
2978429930
** A RowSet in an instance of the following structure.
@@ -29786,15 +29932,17 @@
2978629932
** A typedef of this structure if found in sqliteInt.h.
2978729933
*/
2978829934
struct RowSet {
2978929935
struct RowSetChunk *pChunk; /* List of all chunk allocations */
2979029936
sqlite3 *db; /* The database connection */
29791
- struct RowSetEntry *pEntry; /* List of entries in the rowset */
29937
+ struct RowSetEntry *pEntry; /* List of entries using pRight */
2979229938
struct RowSetEntry *pLast; /* Last entry on the pEntry list */
2979329939
struct RowSetEntry *pFresh; /* Source of new entry objects */
29940
+ struct RowSetEntry *pTree; /* Binary tree of entries */
2979429941
u16 nFresh; /* Number of objects on pFresh */
29795
- u8 isSorted; /* True if content is sorted */
29942
+ u8 isSorted; /* True if pEntry is sorted */
29943
+ u8 iBatch; /* Current insert batch */
2979629944
};
2979729945
2979829946
/*
2979929947
** Turn bulk memory into a RowSet object. N bytes of memory
2980029948
** are available at pSpace. The db pointer is used as a memory context
@@ -29813,29 +29961,34 @@
2981329961
p = pSpace;
2981429962
p->pChunk = 0;
2981529963
p->db = db;
2981629964
p->pEntry = 0;
2981729965
p->pLast = 0;
29966
+ p->pTree = 0;
2981829967
p->pFresh = (struct RowSetEntry*)&p[1];
2981929968
p->nFresh = (u16)((N - sizeof(*p))/sizeof(struct RowSetEntry));
2982029969
p->isSorted = 1;
29970
+ p->iBatch = 0;
2982129971
return p;
2982229972
}
2982329973
2982429974
/*
29825
-** Deallocate all chunks from a RowSet.
29975
+** Deallocate all chunks from a RowSet. This frees all memory that
29976
+** the RowSet has allocated over its lifetime. This routine is
29977
+** the destructor for the RowSet.
2982629978
*/
2982729979
SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
2982829980
struct RowSetChunk *pChunk, *pNextChunk;
2982929981
for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
29830
- pNextChunk = pChunk->pNext;
29982
+ pNextChunk = pChunk->pNextChunk;
2983129983
sqlite3DbFree(p->db, pChunk);
2983229984
}
2983329985
p->pChunk = 0;
2983429986
p->nFresh = 0;
2983529987
p->pEntry = 0;
2983629988
p->pLast = 0;
29989
+ p->pTree = 0;
2983729990
p->isSorted = 1;
2983829991
}
2983929992
2984029993
/*
2984129994
** Insert a new value into a RowSet.
@@ -29842,128 +29995,265 @@
2984229995
**
2984329996
** The mallocFailed flag of the database connection is set if a
2984429997
** memory allocation fails.
2984529998
*/
2984629999
SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
29847
- struct RowSetEntry *pEntry;
29848
- struct RowSetEntry *pLast;
30000
+ struct RowSetEntry *pEntry; /* The new entry */
30001
+ struct RowSetEntry *pLast; /* The last prior entry */
2984930002
assert( p!=0 );
2985030003
if( p->nFresh==0 ){
2985130004
struct RowSetChunk *pNew;
2985230005
pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
2985330006
if( pNew==0 ){
2985430007
return;
2985530008
}
29856
- pNew->pNext = p->pChunk;
30009
+ pNew->pNextChunk = p->pChunk;
2985730010
p->pChunk = pNew;
2985830011
p->pFresh = pNew->aEntry;
2985930012
p->nFresh = ROWSET_ENTRY_PER_CHUNK;
2986030013
}
2986130014
pEntry = p->pFresh++;
2986230015
p->nFresh--;
2986330016
pEntry->v = rowid;
29864
- pEntry->pNext = 0;
30017
+ pEntry->pRight = 0;
2986530018
pLast = p->pLast;
2986630019
if( pLast ){
2986730020
if( p->isSorted && rowid<=pLast->v ){
2986830021
p->isSorted = 0;
2986930022
}
29870
- pLast->pNext = pEntry;
30023
+ pLast->pRight = pEntry;
2987130024
}else{
29872
- assert( p->pEntry==0 );
30025
+ assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
2987330026
p->pEntry = pEntry;
2987430027
}
2987530028
p->pLast = pEntry;
2987630029
}
2987730030
2987830031
/*
29879
-** Merge two lists of RowSet entries. Remove duplicates.
30032
+** Merge two lists of RowSetEntry objects. Remove duplicates.
2988030033
**
29881
-** The input lists are assumed to be in sorted order.
30034
+** The input lists are connected via pRight pointers and are
30035
+** assumed to each already be in sorted order.
2988230036
*/
29883
-static struct RowSetEntry *boolidxMerge(
30037
+static struct RowSetEntry *rowSetMerge(
2988430038
struct RowSetEntry *pA, /* First sorted list to be merged */
2988530039
struct RowSetEntry *pB /* Second sorted list to be merged */
2988630040
){
2988730041
struct RowSetEntry head;
2988830042
struct RowSetEntry *pTail;
2988930043
2989030044
pTail = &head;
2989130045
while( pA && pB ){
29892
- assert( pA->pNext==0 || pA->v<=pA->pNext->v );
29893
- assert( pB->pNext==0 || pB->v<=pB->pNext->v );
30046
+ assert( pA->pRight==0 || pA->v<=pA->pRight->v );
30047
+ assert( pB->pRight==0 || pB->v<=pB->pRight->v );
2989430048
if( pA->v<pB->v ){
29895
- pTail->pNext = pA;
29896
- pA = pA->pNext;
29897
- pTail = pTail->pNext;
30049
+ pTail->pRight = pA;
30050
+ pA = pA->pRight;
30051
+ pTail = pTail->pRight;
2989830052
}else if( pB->v<pA->v ){
29899
- pTail->pNext = pB;
29900
- pB = pB->pNext;
29901
- pTail = pTail->pNext;
30053
+ pTail->pRight = pB;
30054
+ pB = pB->pRight;
30055
+ pTail = pTail->pRight;
2990230056
}else{
29903
- pA = pA->pNext;
30057
+ pA = pA->pRight;
2990430058
}
2990530059
}
2990630060
if( pA ){
29907
- assert( pA->pNext==0 || pA->v<=pA->pNext->v );
29908
- pTail->pNext = pA;
30061
+ assert( pA->pRight==0 || pA->v<=pA->pRight->v );
30062
+ pTail->pRight = pA;
2990930063
}else{
29910
- assert( pB==0 || pB->pNext==0 || pB->v<=pB->pNext->v );
29911
- pTail->pNext = pB;
30064
+ assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
30065
+ pTail->pRight = pB;
2991230066
}
29913
- return head.pNext;
30067
+ return head.pRight;
2991430068
}
2991530069
2991630070
/*
29917
-** Sort all elements of the RowSet into ascending order.
30071
+** Sort all elements on the pEntry list of the RowSet into ascending order.
2991830072
*/
29919
-static void sqlite3RowSetSort(RowSet *p){
30073
+static void rowSetSort(RowSet *p){
2992030074
unsigned int i;
2992130075
struct RowSetEntry *pEntry;
2992230076
struct RowSetEntry *aBucket[40];
2992330077
2992430078
assert( p->isSorted==0 );
2992530079
memset(aBucket, 0, sizeof(aBucket));
2992630080
while( p->pEntry ){
2992730081
pEntry = p->pEntry;
29928
- p->pEntry = pEntry->pNext;
29929
- pEntry->pNext = 0;
30082
+ p->pEntry = pEntry->pRight;
30083
+ pEntry->pRight = 0;
2993030084
for(i=0; aBucket[i]; i++){
29931
- pEntry = boolidxMerge(aBucket[i],pEntry);
30085
+ pEntry = rowSetMerge(aBucket[i], pEntry);
2993230086
aBucket[i] = 0;
2993330087
}
2993430088
aBucket[i] = pEntry;
2993530089
}
2993630090
pEntry = 0;
2993730091
for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
29938
- pEntry = boolidxMerge(pEntry,aBucket[i]);
30092
+ pEntry = rowSetMerge(pEntry, aBucket[i]);
2993930093
}
2994030094
p->pEntry = pEntry;
2994130095
p->pLast = 0;
2994230096
p->isSorted = 1;
2994330097
}
30098
+
2994430099
2994530100
/*
29946
-** Extract the next (smallest) element from the RowSet.
30101
+** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
30102
+** Convert this tree into a linked list connected by the pRight pointers
30103
+** and return pointers to the first and last elements of the new list.
30104
+*/
30105
+static void rowSetTreeToList(
30106
+ struct RowSetEntry *pIn, /* Root of the input tree */
30107
+ struct RowSetEntry **ppFirst, /* Write head of the output list here */
30108
+ struct RowSetEntry **ppLast /* Write tail of the output list here */
30109
+){
30110
+ assert( pIn!=0 );
30111
+ if( pIn->pLeft ){
30112
+ struct RowSetEntry *p;
30113
+ rowSetTreeToList(pIn->pLeft, ppFirst, &p);
30114
+ p->pRight = pIn;
30115
+ }else{
30116
+ *ppFirst = pIn;
30117
+ }
30118
+ if( pIn->pRight ){
30119
+ rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
30120
+ }else{
30121
+ *ppLast = pIn;
30122
+ }
30123
+ assert( (*ppLast)->pRight==0 );
30124
+}
30125
+
30126
+
30127
+/*
30128
+** Convert a sorted list of elements (connected by pRight) into a binary
30129
+** tree with depth of iDepth. A depth of 1 means the tree contains a single
30130
+** node taken from the head of *ppList. A depth of 2 means a tree with
30131
+** three nodes. And so forth.
30132
+**
30133
+** Use as many entries from the input list as required and update the
30134
+** *ppList to point to the unused elements of the list. If the input
30135
+** list contains too few elements, then construct an incomplete tree
30136
+** and leave *ppList set to NULL.
30137
+**
30138
+** Return a pointer to the root of the constructed binary tree.
30139
+*/
30140
+static struct RowSetEntry *rowSetNDeepTree(
30141
+ struct RowSetEntry **ppList,
30142
+ int iDepth
30143
+){
30144
+ struct RowSetEntry *p; /* Root of the new tree */
30145
+ struct RowSetEntry *pLeft; /* Left subtree */
30146
+ if( *ppList==0 ){
30147
+ return 0;
30148
+ }
30149
+ if( iDepth==1 ){
30150
+ p = *ppList;
30151
+ *ppList = p->pRight;
30152
+ p->pLeft = p->pRight = 0;
30153
+ return p;
30154
+ }
30155
+ pLeft = rowSetNDeepTree(ppList, iDepth-1);
30156
+ p = *ppList;
30157
+ if( p==0 ){
30158
+ return pLeft;
30159
+ }
30160
+ p->pLeft = pLeft;
30161
+ *ppList = p->pRight;
30162
+ p->pRight = rowSetNDeepTree(ppList, iDepth-1);
30163
+ return p;
30164
+}
30165
+
30166
+/*
30167
+** Convert a sorted list of elements into a binary tree. Make the tree
30168
+** as deep as it needs to be in order to contain the entire list.
30169
+*/
30170
+static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
30171
+ int iDepth; /* Depth of the tree so far */
30172
+ struct RowSetEntry *p; /* Current tree root */
30173
+ struct RowSetEntry *pLeft; /* Left subtree */
30174
+
30175
+ assert( pList!=0 );
30176
+ p = pList;
30177
+ pList = p->pRight;
30178
+ p->pLeft = p->pRight = 0;
30179
+ for(iDepth=1; pList; iDepth++){
30180
+ pLeft = p;
30181
+ p = pList;
30182
+ pList = p->pRight;
30183
+ p->pLeft = pLeft;
30184
+ p->pRight = rowSetNDeepTree(&pList, iDepth);
30185
+ }
30186
+ return p;
30187
+}
30188
+
30189
+/*
30190
+** Convert the list in p->pEntry into a sorted list if it is not
30191
+** sorted already. If there is a binary tree on p->pTree, then
30192
+** convert it into a list too and merge it into the p->pEntry list.
30193
+*/
30194
+static void rowSetToList(RowSet *p){
30195
+ if( !p->isSorted ){
30196
+ rowSetSort(p);
30197
+ }
30198
+ if( p->pTree ){
30199
+ struct RowSetEntry *pHead, *pTail;
30200
+ rowSetTreeToList(p->pTree, &pHead, &pTail);
30201
+ p->pTree = 0;
30202
+ p->pEntry = rowSetMerge(p->pEntry, pHead);
30203
+ }
30204
+}
30205
+
30206
+/*
30207
+** Extract the smallest element from the RowSet.
2994730208
** Write the element into *pRowid. Return 1 on success. Return
2994830209
** 0 if the RowSet is already empty.
30210
+**
30211
+** After this routine has been called, the sqlite3RowSetInsert()
30212
+** routine may not be called again.
2994930213
*/
2995030214
SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
29951
- if( !p->isSorted ){
29952
- sqlite3RowSetSort(p);
29953
- }
30215
+ rowSetToList(p);
2995430216
if( p->pEntry ){
2995530217
*pRowid = p->pEntry->v;
29956
- p->pEntry = p->pEntry->pNext;
30218
+ p->pEntry = p->pEntry->pRight;
2995730219
if( p->pEntry==0 ){
2995830220
sqlite3RowSetClear(p);
2995930221
}
2996030222
return 1;
2996130223
}else{
2996230224
return 0;
2996330225
}
2996430226
}
30227
+
30228
+/*
30229
+** Check to see if element iRowid was inserted into the the rowset as
30230
+** part of any insert batch prior to iBatch. Return 1 or 0.
30231
+*/
30232
+SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
30233
+ struct RowSetEntry *p;
30234
+ if( iBatch!=pRowSet->iBatch ){
30235
+ if( pRowSet->pEntry ){
30236
+ rowSetToList(pRowSet);
30237
+ pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
30238
+ pRowSet->pEntry = 0;
30239
+ pRowSet->pLast = 0;
30240
+ }
30241
+ pRowSet->iBatch = iBatch;
30242
+ }
30243
+ p = pRowSet->pTree;
30244
+ while( p ){
30245
+ if( p->v<iRowid ){
30246
+ p = p->pRight;
30247
+ }else if( p->v>iRowid ){
30248
+ p = p->pLeft;
30249
+ }else{
30250
+ return 1;
30251
+ }
30252
+ }
30253
+ return 0;
30254
+}
2996530255
2996630256
/************** End of rowset.c **********************************************/
2996730257
/************** Begin file pager.c *******************************************/
2996830258
/*
2996930259
** 2001 September 15
@@ -29983,11 +30273,11 @@
2998330273
** is separate from the database file. The pager also implements file
2998430274
** locking to prevent two processes from writing the same database
2998530275
** file simultaneously, or one process from reading the database while
2998630276
** another is writing.
2998730277
**
29988
-** @(#) $Id: pager.c,v 1.580 2009/04/11 16:27:50 drh Exp $
30278
+** @(#) $Id: pager.c,v 1.586 2009/05/06 18:57:10 shane Exp $
2998930279
*/
2999030280
#ifndef SQLITE_OMIT_DISKIO
2999130281
2999230282
/*
2999330283
** Macros for troubleshooting. Normally turned off
@@ -30193,10 +30483,16 @@
3019330483
** needSync
3019430484
**
3019530485
** TODO: It might be easier to set this variable in writeJournalHdr()
3019630486
** and writeMasterJournal() only. Change its meaning to "unsynced data
3019730487
** has been written to the journal".
30488
+**
30489
+** subjInMemory
30490
+**
30491
+** This is a boolean variable. If true, then any required sub-journal
30492
+** is opened as an in-memory journal file. If false, then in-memory
30493
+** sub-journals are only used for in-memory pager files.
3019830494
*/
3019930495
struct Pager {
3020030496
sqlite3_vfs *pVfs; /* OS functions to use for IO */
3020130497
u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
3020230498
u8 journalMode; /* On of the PAGER_JOURNALMODE_* values */
@@ -30226,10 +30522,11 @@
3022630522
u8 journalStarted; /* True if header of journal is synced */
3022730523
u8 changeCountDone; /* Set after incrementing the change-counter */
3022830524
u8 setMaster; /* True if a m-j name has been written to jrnl */
3022930525
u8 doNotSync; /* Boolean. While true, do not spill the cache */
3023030526
u8 dbSizeValid; /* Set when dbSize is correct */
30527
+ u8 subjInMemory; /* True to use in-memory sub-journals */
3023130528
Pgno dbSize; /* Number of pages in the database */
3023230529
Pgno dbOrigSize; /* dbSize before the current transaction */
3023330530
Pgno dbFileSize; /* Number of pages in the database file */
3023430531
int errCode; /* One of several kinds of errors */
3023530532
int nRec; /* Pages journalled since last j-header written */
@@ -31005,10 +31302,11 @@
3100531302
*/
3100631303
static void pager_reset(Pager *pPager){
3100731304
if( SQLITE_OK==pPager->errCode ){
3100831305
sqlite3BackupRestart(pPager->pBackup);
3100931306
sqlite3PcacheClear(pPager->pPCache);
31307
+ pPager->dbSizeValid = 0;
3101031308
}
3101131309
}
3101231310
3101331311
/*
3101431312
** Free all structures in the Pager.aSavepoint[] array and set both
@@ -31018,11 +31316,11 @@
3101831316
static void releaseAllSavepoints(Pager *pPager){
3101931317
int ii; /* Iterator for looping through Pager.aSavepoint */
3102031318
for(ii=0; ii<pPager->nSavepoint; ii++){
3102131319
sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
3102231320
}
31023
- if( !pPager->exclusiveMode ){
31321
+ if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
3102431322
sqlite3OsClose(pPager->sjfd);
3102531323
}
3102631324
sqlite3_free(pPager->aSavepoint);
3102731325
pPager->aSavepoint = 0;
3102831326
pPager->nSavepoint = 0;
@@ -31254,11 +31552,15 @@
3125431552
sqlite3OsClose(pPager->jfd);
3125531553
if( !isMemoryJournal ){
3125631554
rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
3125731555
}
3125831556
}else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
31259
- rc = sqlite3OsTruncate(pPager->jfd, 0);
31557
+ if( pPager->journalOff==0 ){
31558
+ rc = SQLITE_OK;
31559
+ }else{
31560
+ rc = sqlite3OsTruncate(pPager->jfd, 0);
31561
+ }
3126031562
pPager->journalOff = 0;
3126131563
pPager->journalStarted = 0;
3126231564
}else if( pPager->exclusiveMode
3126331565
|| pPager->journalMode==PAGER_JOURNALMODE_PERSIST
3126431566
){
@@ -33143,11 +33445,11 @@
3314333445
ROUND8(pVfs->szOsFile) + /* The main db file */
3314433446
journalFileSize * 2 + /* The two journal files */
3314533447
nPathname + 1 + /* zFilename */
3314633448
nPathname + 8 + 1 /* zJournal */
3314733449
);
33148
- assert( EIGHT_BYTE_ALIGNMENT(journalFileSize) );
33450
+ assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
3314933451
if( !pPtr ){
3315033452
sqlite3_free(zPathname);
3315133453
return SQLITE_NOMEM;
3315233454
}
3315333455
pPager = (Pager*)(pPtr);
@@ -33628,13 +33930,19 @@
3362833930
}
3362933931
3363033932
/*
3363133933
** If the reference count has reached zero, rollback any active
3363233934
** transaction and unlock the pager.
33935
+**
33936
+** Except, in locking_mode=EXCLUSIVE when there is nothing to in
33937
+** the rollback journal, the unlock is not performed and there is
33938
+** nothing to rollback, so this routine is a no-op.
3363333939
*/
3363433940
static void pagerUnlockIfUnused(Pager *pPager){
33635
- if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
33941
+ if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
33942
+ && (!pPager->exclusiveMode || pPager->journalOff>0)
33943
+ ){
3363633944
pagerUnlockAndRollback(pPager);
3363733945
}
3363833946
}
3363933947
3364033948
/*
@@ -33858,11 +34166,11 @@
3385834166
** sqlite3OsOpen() fails.
3385934167
*/
3386034168
static int openSubJournal(Pager *pPager){
3386134169
int rc = SQLITE_OK;
3386234170
if( isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ){
33863
- if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
34171
+ if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
3386434172
sqlite3MemJournalOpen(pPager->sjfd);
3386534173
}else{
3386634174
rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
3386734175
}
3386834176
}
@@ -33977,14 +34285,23 @@
3397734285
** of the journal file is deferred until there is an actual need to
3397834286
** write to the journal. TODO: Why handle temporary files differently?
3397934287
**
3398034288
** If the journal file is opened (or if it is already open), then a
3398134289
** journal-header is written to the start of it.
34290
+**
34291
+** If the subjInMemory argument is non-zero, then any sub-journal opened
34292
+** within this transaction will be opened as an in-memory file. This
34293
+** has no effect if the sub-journal is already opened (as it may be when
34294
+** running in exclusive mode) or if the transaction does not require a
34295
+** sub-journal. If the subjInMemory argument is zero, then any required
34296
+** sub-journal is implemented in-memory if pPager is an in-memory database,
34297
+** or using a temporary file otherwise.
3398234298
*/
33983
-SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag){
34299
+SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
3398434300
int rc = SQLITE_OK;
3398534301
assert( pPager->state!=PAGER_UNLOCK );
34302
+ pPager->subjInMemory = (u8)subjInMemory;
3398634303
if( pPager->state==PAGER_SHARED ){
3398734304
assert( pPager->pInJournal==0 );
3398834305
assert( !MEMDB && !pPager->tempFile );
3398934306
3399034307
/* Obtain a RESERVED lock on the database file. If the exFlag parameter
@@ -34065,11 +34382,11 @@
3406534382
**
3406634383
** First check to see that the transaction journal exists and
3406734384
** create it if it does not.
3406834385
*/
3406934386
assert( pPager->state!=PAGER_UNLOCK );
34070
- rc = sqlite3PagerBegin(pPager, 0);
34387
+ rc = sqlite3PagerBegin(pPager, 0, pPager->subjInMemory);
3407134388
if( rc!=SQLITE_OK ){
3407234389
return rc;
3407334390
}
3407434391
assert( pPager->state>=PAGER_RESERVED );
3407534392
if( !isOpen(pPager->jfd) && pPager->useJournal
@@ -35148,15 +35465,18 @@
3514835465
** PAGER_JOURNALMODE_TRUNCATE
3514935466
** PAGER_JOURNALMODE_PERSIST
3515035467
** PAGER_JOURNALMODE_OFF
3515135468
** PAGER_JOURNALMODE_MEMORY
3515235469
**
35153
-** If the parameter is not _QUERY, then the journal-mode is set to the
35154
-** value specified. Except, an in-memory database can only have its
35155
-** journal mode set to _OFF or _MEMORY. Attempts to change the journal
35156
-** mode of an in-memory database to something other than _OFF or _MEMORY
35157
-** are silently ignored.
35470
+** If the parameter is not _QUERY, then the journal_mode is set to the
35471
+** value specified if the change is allowed. The change is disallowed
35472
+** for the following reasons:
35473
+**
35474
+** * An in-memory database can only have its journal_mode set to _OFF
35475
+** or _MEMORY.
35476
+**
35477
+** * The journal mode may not be changed while a transaction is active.
3515835478
**
3515935479
** The returned indicate the current (possibly updated) journal-mode.
3516035480
*/
3516135481
SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
3516235482
assert( eMode==PAGER_JOURNALMODE_QUERY
@@ -35164,12 +35484,19 @@
3516435484
|| eMode==PAGER_JOURNALMODE_TRUNCATE
3516535485
|| eMode==PAGER_JOURNALMODE_PERSIST
3516635486
|| eMode==PAGER_JOURNALMODE_OFF
3516735487
|| eMode==PAGER_JOURNALMODE_MEMORY );
3516835488
assert( PAGER_JOURNALMODE_QUERY<0 );
35169
- if( eMode>=0 && (!MEMDB || eMode==PAGER_JOURNALMODE_MEMORY
35170
- || eMode==PAGER_JOURNALMODE_OFF) ){
35489
+ if( eMode>=0
35490
+ && (!MEMDB || eMode==PAGER_JOURNALMODE_MEMORY
35491
+ || eMode==PAGER_JOURNALMODE_OFF)
35492
+ && !pPager->dbModified
35493
+ && (!isOpen(pPager->jfd) || 0==pPager->journalOff)
35494
+ ){
35495
+ if( isOpen(pPager->jfd) ){
35496
+ sqlite3OsClose(pPager->jfd);
35497
+ }
3517135498
pPager->journalMode = (u8)eMode;
3517235499
}
3517335500
return (int)pPager->journalMode;
3517435501
}
3517535502
@@ -36210,11 +36537,11 @@
3621036537
** May you do good and not evil.
3621136538
** May you find forgiveness for yourself and forgive others.
3621236539
** May you share freely, never taking more than you give.
3621336540
**
3621436541
*************************************************************************
36215
-** $Id: btree.c,v 1.595 2009/04/11 16:06:15 danielk1977 Exp $
36542
+** $Id: btree.c,v 1.608 2009/05/06 18:57:10 shane Exp $
3621636543
**
3621736544
** This file implements a external (disk-based) database using BTrees.
3621836545
** See the header comment on "btreeInt.h" for additional information.
3621936546
** Including a description of file format and an overview of operation.
3622036547
*/
@@ -36962,22 +37289,63 @@
3696237289
** Compute the total number of bytes that a Cell needs in the cell
3696337290
** data area of the btree-page. The return number includes the cell
3696437291
** data header and the local payload, but not any overflow page or
3696537292
** the space used by the cell pointer.
3696637293
*/
37294
+static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
37295
+ u8 *pIter = &pCell[pPage->childPtrSize];
37296
+ u32 nSize;
37297
+
37298
+#ifdef SQLITE_DEBUG
37299
+ /* The value returned by this function should always be the same as
37300
+ ** the (CellInfo.nSize) value found by doing a full parse of the
37301
+ ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
37302
+ ** this function verifies that this invariant is not violated. */
37303
+ CellInfo debuginfo;
37304
+ sqlite3BtreeParseCellPtr(pPage, pCell, &debuginfo);
37305
+#endif
37306
+
37307
+ if( pPage->intKey ){
37308
+ u8 *pEnd;
37309
+ if( pPage->hasData ){
37310
+ pIter += getVarint32(pIter, nSize);
37311
+ }else{
37312
+ nSize = 0;
37313
+ }
37314
+
37315
+ /* pIter now points at the 64-bit integer key value, a variable length
37316
+ ** integer. The following block moves pIter to point at the first byte
37317
+ ** past the end of the key value. */
37318
+ pEnd = &pIter[9];
37319
+ while( (*pIter++)&0x80 && pIter<pEnd );
37320
+ }else{
37321
+ pIter += getVarint32(pIter, nSize);
37322
+ }
37323
+
37324
+ if( nSize>pPage->maxLocal ){
37325
+ int minLocal = pPage->minLocal;
37326
+ nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
37327
+ if( nSize>pPage->maxLocal ){
37328
+ nSize = minLocal;
37329
+ }
37330
+ nSize += 4;
37331
+ }
37332
+ nSize += (pIter - pCell);
37333
+
37334
+ /* The minimum size of any cell is 4 bytes. */
37335
+ if( nSize<4 ){
37336
+ nSize = 4;
37337
+ }
37338
+
37339
+ assert( nSize==debuginfo.nSize );
37340
+ return (u16)nSize;
37341
+}
3696737342
#ifndef NDEBUG
3696837343
static u16 cellSize(MemPage *pPage, int iCell){
36969
- CellInfo info;
36970
- sqlite3BtreeParseCell(pPage, iCell, &info);
36971
- return info.nSize;
37344
+ return cellSizePtr(pPage, findCell(pPage, iCell));
3697237345
}
3697337346
#endif
36974
-static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
36975
- CellInfo info;
36976
- sqlite3BtreeParseCellPtr(pPage, pCell, &info);
36977
- return info.nSize;
36978
-}
3697937347
3698037348
#ifndef SQLITE_OMIT_AUTOVACUUM
3698137349
/*
3698237350
** If the cell pCell, part of page pPage contains a pointer
3698337351
** to an overflow page, insert an entry into the pointer-map
@@ -37120,17 +37488,17 @@
3712037488
for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
3712137489
int size = get2byte(&data[pc+2]); /* Size of free slot */
3712237490
if( size>=nByte ){
3712337491
int x = size - nByte;
3712437492
if( x<4 ){
37125
- /* Remove the slot from the free-list. Update the number of
37126
- ** fragmented bytes within the page. */
37493
+ /* Remove the slot from the free-list. Update the number of
37494
+ ** fragmented bytes within the page. */
3712737495
memcpy(&data[addr], &data[pc], 2);
3712837496
data[hdr+7] = (u8)(nFrag + x);
3712937497
}else{
37130
- /* The slot remains on the free-list. Reduce its size to account
37131
- ** for the portion used by the new allocation. */
37498
+ /* The slot remains on the free-list. Reduce its size to account
37499
+ ** for the portion used by the new allocation. */
3713237500
put2byte(&data[pc+2], x);
3713337501
}
3713437502
return pc + x;
3713537503
}
3713637504
}
@@ -37560,10 +37928,16 @@
3756037928
** zFilename is the name of the database file. If zFilename is NULL
3756137929
** a new database with a random name is created. This randomly named
3756237930
** database file will be deleted when sqlite3BtreeClose() is called.
3756337931
** If zFilename is ":memory:" then an in-memory database is created
3756437932
** that is automatically destroyed when it is closed.
37933
+**
37934
+** If the database is already opened in the same database connection
37935
+** and we are in shared cache mode, then the open will fail with an
37936
+** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
37937
+** objects in the same database connection since doing so will lead
37938
+** to problems with locking.
3756537939
*/
3756637940
SQLITE_PRIVATE int sqlite3BtreeOpen(
3756737941
const char *zFilename, /* Name of the file containing the BTree database */
3756837942
sqlite3 *db, /* Associated database handle */
3756937943
Btree **ppBtree, /* Pointer to new Btree object written here */
@@ -37625,10 +37999,21 @@
3762537999
sqlite3_mutex_enter(mutexShared);
3762638000
for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
3762738001
assert( pBt->nRef>0 );
3762838002
if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
3762938003
&& sqlite3PagerVfs(pBt->pPager)==pVfs ){
38004
+ int iDb;
38005
+ for(iDb=db->nDb-1; iDb>=0; iDb--){
38006
+ Btree *pExisting = db->aDb[iDb].pBt;
38007
+ if( pExisting && pExisting->pBt==pBt ){
38008
+ sqlite3_mutex_leave(mutexShared);
38009
+ sqlite3_mutex_leave(mutexOpen);
38010
+ sqlite3_free(zFullPathname);
38011
+ sqlite3_free(p);
38012
+ return SQLITE_CONSTRAINT;
38013
+ }
38014
+ }
3763038015
p->pBt = pBt;
3763138016
pBt->nRef++;
3763238017
break;
3763338018
}
3763438019
}
@@ -37682,11 +38067,10 @@
3768238067
pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
3768338068
pBt->pageSize = get2byte(&zDbHeader[16]);
3768438069
if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
3768538070
|| ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
3768638071
pBt->pageSize = 0;
37687
- sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
3768838072
#ifndef SQLITE_OMIT_AUTOVACUUM
3768938073
/* If the magic name ":memory:" will create an in-memory database, then
3769038074
** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
3769138075
** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
3769238076
** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
@@ -37704,13 +38088,14 @@
3770438088
#ifndef SQLITE_OMIT_AUTOVACUUM
3770538089
pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
3770638090
pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
3770738091
#endif
3770838092
}
38093
+ rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
38094
+ if( rc ) goto btree_open_out;
3770938095
pBt->usableSize = pBt->pageSize - nReserve;
3771038096
assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
37711
- sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
3771238097
3771338098
#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
3771438099
/* Add the new BtShared object to the linked list sharable BtShareds.
3771538100
*/
3771638101
if( p->sharable ){
@@ -38150,11 +38535,12 @@
3815038535
*/
3815138536
releasePage(pPage1);
3815238537
pBt->usableSize = (u16)usableSize;
3815338538
pBt->pageSize = (u16)pageSize;
3815438539
freeTempSpace(pBt);
38155
- sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
38540
+ rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
38541
+ if( rc ) goto page1_init_failed;
3815638542
return SQLITE_OK;
3815738543
}
3815838544
if( usableSize<500 ){
3815938545
goto page1_init_failed;
3816038546
}
@@ -38229,18 +38615,10 @@
3822938615
static void unlockBtreeIfUnused(BtShared *pBt){
3823038616
assert( sqlite3_mutex_held(pBt->mutex) );
3823138617
if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
3823238618
if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
3823338619
assert( pBt->pPage1->aData );
38234
-#if 0
38235
- if( pBt->pPage1->aData==0 ){
38236
- MemPage *pPage = pBt->pPage1;
38237
- pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
38238
- pPage->pBt = pBt;
38239
- pPage->pgno = 1;
38240
- }
38241
-#endif
3824238620
releasePage(pBt->pPage1);
3824338621
}
3824438622
pBt->pPage1 = 0;
3824538623
}
3824638624
}
@@ -38379,11 +38757,11 @@
3837938757
3838038758
if( rc==SQLITE_OK && wrflag ){
3838138759
if( pBt->readOnly ){
3838238760
rc = SQLITE_READONLY;
3838338761
}else{
38384
- rc = sqlite3PagerBegin(pBt->pPager, wrflag>1);
38762
+ rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
3838538763
if( rc==SQLITE_OK ){
3838638764
rc = newDatabase(pBt);
3838738765
}
3838838766
}
3838938767
}
@@ -38829,11 +39207,11 @@
3882939207
** the journal. Then the contents of the journal are flushed out to
3883039208
** the disk. After the journal is safely on oxide, the changes to the
3883139209
** database are written into the database file and flushed to oxide.
3883239210
** At the end of this call, the rollback journal still exists on the
3883339211
** disk and we are still holding all locks, so the transaction has not
38834
-** committed. See sqlite3BtreeCommit() for the second phase of the
39212
+** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
3883539213
** commit process.
3883639214
**
3883739215
** This call is a no-op if no write-transaction is currently active on pBt.
3883839216
**
3883939217
** Otherwise, sync the database file for the btree pBt. zMaster points to
@@ -38869,16 +39247,17 @@
3886939247
3887039248
/*
3887139249
** Commit the transaction currently in progress.
3887239250
**
3887339251
** This routine implements the second phase of a 2-phase commit. The
38874
-** sqlite3BtreeSync() routine does the first phase and should be invoked
38875
-** prior to calling this routine. The sqlite3BtreeSync() routine did
38876
-** all the work of writing information out to disk and flushing the
39252
+** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
39253
+** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
39254
+** routine did all the work of writing information out to disk and flushing the
3887739255
** contents so that they are written onto the disk platter. All this
38878
-** routine has to do is delete or truncate the rollback journal
38879
-** (which causes the transaction to commit) and drop locks.
39256
+** routine has to do is delete or truncate or zero the header in the
39257
+** the rollback journal (which causes the transaction to commit) and
39258
+** drop locks.
3888039259
**
3888139260
** This will release the write lock on the database file. If there
3888239261
** are no active cursors, it also releases the read lock.
3888339262
*/
3888439263
SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
@@ -38913,11 +39292,11 @@
3891339292
if( 0==pBt->nTransaction ){
3891439293
pBt->inTransaction = TRANS_NONE;
3891539294
}
3891639295
}
3891739296
38918
- /* Set the handles current transaction state to TRANS_NONE and unlock
39297
+ /* Set the current transaction state to TRANS_NONE and unlock
3891939298
** the pager if this call closed the only read or write transaction.
3892039299
*/
3892139300
btreeClearHasContent(pBt);
3892239301
p->inTrans = TRANS_NONE;
3892339302
unlockBtreeIfUnused(pBt);
@@ -40069,20 +40448,35 @@
4006940448
SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
4007040449
int rc;
4007140450
4007240451
assert( cursorHoldsMutex(pCur) );
4007340452
assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
40453
+
40454
+ /* If the cursor already points to the last entry, this is a no-op. */
40455
+ if( CURSOR_VALID==pCur->eState && pCur->atLast ){
40456
+#ifdef SQLITE_DEBUG
40457
+ /* This block serves to assert() that the cursor really does point
40458
+ ** to the last entry in the b-tree. */
40459
+ int ii;
40460
+ for(ii=0; ii<pCur->iPage; ii++){
40461
+ assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
40462
+ }
40463
+ assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
40464
+ assert( pCur->apPage[pCur->iPage]->leaf );
40465
+#endif
40466
+ return SQLITE_OK;
40467
+ }
40468
+
4007440469
rc = moveToRoot(pCur);
4007540470
if( rc==SQLITE_OK ){
4007640471
if( CURSOR_INVALID==pCur->eState ){
4007740472
assert( pCur->apPage[pCur->iPage]->nCell==0 );
4007840473
*pRes = 1;
4007940474
}else{
4008040475
assert( pCur->eState==CURSOR_VALID );
4008140476
*pRes = 0;
4008240477
rc = moveToRightmost(pCur);
40083
- getCellInfo(pCur);
4008440478
pCur->atLast = rc==SQLITE_OK ?1:0;
4008540479
}
4008640480
}
4008740481
return rc;
4008840482
}
@@ -40169,18 +40563,17 @@
4016940563
pCur->aiIdx[pCur->iPage] = (u16)upr;
4017040564
}else{
4017140565
pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
4017240566
}
4017340567
for(;;){
40174
- void *pCellKey;
40175
- i64 nCellKey;
40176
- int idx = pCur->aiIdx[pCur->iPage];
40568
+ int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
40569
+ u8 *pCell; /* Pointer to current cell in pPage */
40570
+
4017740571
pCur->info.nSize = 0;
40178
- pCur->validNKey = 1;
40572
+ pCell = findCell(pPage, idx) + pPage->childPtrSize;
4017940573
if( pPage->intKey ){
40180
- u8 *pCell;
40181
- pCell = findCell(pPage, idx) + pPage->childPtrSize;
40574
+ i64 nCellKey;
4018240575
if( pPage->hasData ){
4018340576
u32 dummy;
4018440577
pCell += getVarint32(pCell, dummy);
4018540578
}
4018640579
getVarint(pCell, (u64*)&nCellKey);
@@ -40190,30 +40583,54 @@
4019040583
c = -1;
4019140584
}else{
4019240585
assert( nCellKey>intKey );
4019340586
c = +1;
4019440587
}
40195
- }else{
40196
- int available;
40197
- pCellKey = (void *)fetchPayload(pCur, &available, 0);
40198
- nCellKey = pCur->info.nKey;
40199
- if( available>=nCellKey ){
40200
- c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
40201
- }else{
40202
- pCellKey = sqlite3Malloc( (int)nCellKey );
40588
+ pCur->validNKey = 1;
40589
+ pCur->info.nKey = nCellKey;
40590
+ }else{
40591
+ /* The maximum supported page-size is 32768 bytes. This means that
40592
+ ** the maximum number of record bytes stored on an index B-Tree
40593
+ ** page is at most 8198 bytes, which may be stored as a 2-byte
40594
+ ** varint. This information is used to attempt to avoid parsing
40595
+ ** the entire cell by checking for the cases where the record is
40596
+ ** stored entirely within the b-tree page by inspecting the first
40597
+ ** 2 bytes of the cell.
40598
+ */
40599
+ int nCell = pCell[0];
40600
+ if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
40601
+ /* This branch runs if the record-size field of the cell is a
40602
+ ** single byte varint and the record fits entirely on the main
40603
+ ** b-tree page. */
40604
+ c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
40605
+ }else if( !(pCell[1] & 0x80)
40606
+ && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
40607
+ ){
40608
+ /* The record-size field is a 2 byte varint and the record
40609
+ ** fits entirely on the main b-tree page. */
40610
+ c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
40611
+ }else{
40612
+ /* The record flows over onto one or more overflow pages. In
40613
+ ** this case the whole cell needs to be parsed, a buffer allocated
40614
+ ** and accessPayload() used to retrieve the record into the
40615
+ ** buffer before VdbeRecordCompare() can be called. */
40616
+ void *pCellKey;
40617
+ u8 * const pCellBody = pCell - pPage->childPtrSize;
40618
+ sqlite3BtreeParseCellPtr(pPage, pCellBody, &pCur->info);
40619
+ nCell = (int)pCur->info.nKey;
40620
+ pCellKey = sqlite3Malloc( nCell );
4020340621
if( pCellKey==0 ){
4020440622
rc = SQLITE_NOMEM;
4020540623
goto moveto_finish;
4020640624
}
40207
- rc = sqlite3BtreeKey(pCur, 0, (int)nCellKey, (void*)pCellKey);
40208
- c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
40625
+ rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0, 0);
40626
+ c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
4020940627
sqlite3_free(pCellKey);
4021040628
if( rc ) goto moveto_finish;
4021140629
}
4021240630
}
4021340631
if( c==0 ){
40214
- pCur->info.nKey = nCellKey;
4021540632
if( pPage->intKey && !pPage->leaf ){
4021640633
lwr = idx;
4021740634
upr = lwr - 1;
4021840635
break;
4021940636
}else{
@@ -40226,11 +40643,10 @@
4022640643
lwr = idx+1;
4022740644
}else{
4022840645
upr = idx-1;
4022940646
}
4023040647
if( lwr>upr ){
40231
- pCur->info.nKey = nCellKey;
4023240648
break;
4023340649
}
4023440650
pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
4023540651
}
4023640652
assert( lwr==upr+1 );
@@ -41187,11 +41603,11 @@
4118741603
** the entry for the overflow page into the pointer map.
4118841604
*/
4118941605
CellInfo info;
4119041606
sqlite3BtreeParseCellPtr(pPage, pCell, &info);
4119141607
assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
41192
- if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
41608
+ if( info.iOverflow ){
4119341609
Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
4119441610
rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
4119541611
if( rc!=SQLITE_OK ) return rc;
4119641612
}
4119741613
}
@@ -41210,43 +41626,36 @@
4121041626
int nCell, /* The number of cells to add to this page */
4121141627
u8 **apCell, /* Pointers to cell bodies */
4121241628
u16 *aSize /* Sizes of the cells */
4121341629
){
4121441630
int i; /* Loop counter */
41215
- int totalSize; /* Total size of all cells */
41216
- int hdr; /* Index of page header */
41217
- int cellptr; /* Address of next cell pointer */
41631
+ u8 *pCellptr; /* Address of next cell pointer */
4121841632
int cellbody; /* Address of next cell body */
41219
- u8 *data; /* Data for the page */
41633
+ u8 * const data = pPage->aData; /* Pointer to data for pPage */
41634
+ const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
41635
+ const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
4122041636
4122141637
assert( pPage->nOverflow==0 );
4122241638
assert( sqlite3_mutex_held(pPage->pBt->mutex) );
4122341639
assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
41224
- totalSize = 0;
41225
- for(i=0; i<nCell; i++){
41226
- totalSize += aSize[i];
41227
- }
41228
- assert( totalSize+2*nCell<=pPage->nFree );
41640
+ assert( sqlite3PagerIswriteable(pPage->pDbPage) );
41641
+
41642
+ /* Check that the page has just been zeroed by zeroPage() */
4122941643
assert( pPage->nCell==0 );
41230
- assert( sqlite3PagerIswriteable(pPage->pDbPage) );
41231
- cellptr = pPage->cellOffset;
41232
- data = pPage->aData;
41233
- hdr = pPage->hdrOffset;
41644
+ assert( get2byte(&data[hdr+5])==nUsable );
41645
+
41646
+ pCellptr = &data[pPage->cellOffset + nCell*2];
41647
+ cellbody = nUsable;
41648
+ for(i=nCell-1; i>=0; i--){
41649
+ pCellptr -= 2;
41650
+ cellbody -= aSize[i];
41651
+ put2byte(pCellptr, cellbody);
41652
+ memcpy(&data[cellbody], apCell[i], aSize[i]);
41653
+ }
4123441654
put2byte(&data[hdr+3], nCell);
41235
- if( nCell ){
41236
- cellbody = allocateSpace(pPage, totalSize);
41237
- assert( cellbody>0 );
41238
- assert( pPage->nFree >= 2*nCell );
41239
- pPage->nFree -= 2*nCell;
41240
- for(i=0; i<nCell; i++){
41241
- put2byte(&data[cellptr], cellbody);
41242
- memcpy(&data[cellbody], apCell[i], aSize[i]);
41243
- cellptr += 2;
41244
- cellbody += aSize[i];
41245
- }
41246
- assert( cellbody==pPage->pBt->usableSize );
41247
- }
41655
+ put2byte(&data[hdr+5], cellbody);
41656
+ pPage->nFree -= (nCell*2 + nUsable - cellbody);
4124841657
pPage->nCell = (u16)nCell;
4124941658
}
4125041659
4125141660
/*
4125241661
** The following parameters determine how many adjacent pages get involved
@@ -42274,20 +42683,32 @@
4227442683
** define what table the record should be inserted into. The cursor
4227542684
** is left pointing at a random location.
4227642685
**
4227742686
** For an INTKEY table, only the nKey value of the key is used. pKey is
4227842687
** ignored. For a ZERODATA table, the pData and nData are both ignored.
42688
+**
42689
+** If the seekResult parameter is non-zero, then a successful call to
42690
+** sqlite3BtreeMoveto() to seek cursor pCur to (pKey, nKey) has already
42691
+** been performed. seekResult is the search result returned (a negative
42692
+** number if pCur points at an entry that is smaller than (pKey, nKey), or
42693
+** a positive value if pCur points at an etry that is larger than
42694
+** (pKey, nKey)).
42695
+**
42696
+** If the seekResult parameter is 0, then cursor pCur may point to any
42697
+** entry or to no entry at all. In this case this function has to seek
42698
+** the cursor before the new key can be inserted.
4227942699
*/
4228042700
SQLITE_PRIVATE int sqlite3BtreeInsert(
4228142701
BtCursor *pCur, /* Insert data into the table of this cursor */
4228242702
const void *pKey, i64 nKey, /* The key of the new record */
4228342703
const void *pData, int nData, /* The data of the new record */
4228442704
int nZero, /* Number of extra 0 bytes to append to data */
42285
- int appendBias /* True if this is likely an append */
42705
+ int appendBias, /* True if this is likely an append */
42706
+ int seekResult /* Result of prior sqlite3BtreeMoveto() call */
4228642707
){
4228742708
int rc;
42288
- int loc;
42709
+ int loc = seekResult;
4228942710
int szNew;
4229042711
int idx;
4229142712
MemPage *pPage;
4229242713
Btree *p = pCur->pBtree;
4229342714
BtShared *pBt = p->pBt;
@@ -42306,16 +42727,25 @@
4230642727
}
4230742728
if( pCur->eState==CURSOR_FAULT ){
4230842729
return pCur->skip;
4230942730
}
4231042731
42311
- /* Save the positions of any other cursors open on this table */
42312
- sqlite3BtreeClearCursor(pCur);
42313
- if(
42314
- SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
42732
+ /* Save the positions of any other cursors open on this table.
42733
+ **
42734
+ ** In some cases, the call to sqlite3BtreeMoveto() below is a no-op. For
42735
+ ** example, when inserting data into a table with auto-generated integer
42736
+ ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
42737
+ ** integer key to use. It then calls this function to actually insert the
42738
+ ** data into the intkey B-Tree. In this case sqlite3BtreeMoveto() recognizes
42739
+ ** that the cursor is already where it needs to be and returns without
42740
+ ** doing any work. To avoid thwarting these optimizations, it is important
42741
+ ** not to clear the cursor here.
42742
+ */
42743
+ if(
42744
+ SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) || (!loc &&
4231542745
SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
42316
- ){
42746
+ )){
4231742747
return rc;
4231842748
}
4231942749
4232042750
pPage = pCur->apPage[pCur->iPage];
4232142751
assert( pPage->intKey || nKey>=0 );
@@ -42357,21 +42787,46 @@
4235742787
pCur->validNKey = 0;
4235842788
}else{
4235942789
assert( pPage->leaf );
4236042790
}
4236142791
rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
42362
- if( rc==SQLITE_OK ){
42792
+ assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
42793
+
42794
+ /* If no error has occured, call balance() to deal with any overflow and
42795
+ ** move the cursor to point at the root of the table (since balance may
42796
+ ** have rearranged the table in such a way as to invalidate BtCursor.apPage[]
42797
+ ** or BtCursor.aiIdx[]).
42798
+ **
42799
+ ** Except, if all of the following are true, do nothing:
42800
+ **
42801
+ ** * Inserting the new cell did not cause overflow,
42802
+ **
42803
+ ** * Before inserting the new cell the cursor was pointing at the
42804
+ ** largest key in an intkey B-Tree, and
42805
+ **
42806
+ ** * The key value associated with the new cell is now the largest
42807
+ ** in the B-Tree.
42808
+ **
42809
+ ** In this case the cursor can be safely left pointing at the (new)
42810
+ ** largest key value in the B-Tree. Doing so speeds up inserting a set
42811
+ ** of entries with increasing integer key values via a single cursor
42812
+ ** (comes up with "INSERT INTO ... SELECT ..." statements), as
42813
+ ** the next insert operation is not required to seek the cursor.
42814
+ */
42815
+ if( rc==SQLITE_OK
42816
+ && (pPage->nOverflow || !pCur->atLast || loc>=0 || !pCur->apPage[0]->intKey)
42817
+ ){
4236342818
rc = balance(pCur, 1);
42819
+ if( rc==SQLITE_OK ){
42820
+ moveToRoot(pCur);
42821
+ }
4236442822
}
42365
-
42823
+
4236642824
/* Must make sure nOverflow is reset to zero even if the balance()
4236742825
** fails. Internal data structure corruption will result otherwise. */
4236842826
pCur->apPage[pCur->iPage]->nOverflow = 0;
4236942827
42370
- if( rc==SQLITE_OK ){
42371
- moveToRoot(pCur);
42372
- }
4237342828
end_insert:
4237442829
return rc;
4237542830
}
4237642831
4237742832
/*
@@ -43199,11 +43654,11 @@
4319943654
u8 ePtrmapType;
4320043655
Pgno iPtrmapParent;
4320143656
4320243657
rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
4320343658
if( rc!=SQLITE_OK ){
43204
- if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
43659
+ if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
4320543660
checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
4320643661
return;
4320743662
}
4320843663
4320943664
if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
@@ -43326,11 +43781,11 @@
4332643781
pBt = pCheck->pBt;
4332743782
usableSize = pBt->usableSize;
4332843783
if( iPage==0 ) return 0;
4332943784
if( checkRef(pCheck, iPage, zParentContext) ) return 0;
4333043785
if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
43331
- if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
43786
+ if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
4333243787
checkAppendMsg(pCheck, zContext,
4333343788
"unable to get the page. error code=%d", rc);
4333443789
return 0;
4333543790
}
4333643791
if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
@@ -44398,11 +44853,11 @@
4439844853
** This file contains code use to manipulate "Mem" structure. A "Mem"
4439944854
** stores a single value in the VDBE. Mem is an opaque structure visible
4440044855
** only within the VDBE. Interface routines refer to a Mem using the
4440144856
** name sqlite_value
4440244857
**
44403
-** $Id: vdbemem.c,v 1.140 2009/04/05 12:22:09 drh Exp $
44858
+** $Id: vdbemem.c,v 1.144 2009/05/05 12:54:50 drh Exp $
4440444859
*/
4440544860
4440644861
/*
4440744862
** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
4440844863
** P if required.
@@ -44651,20 +45106,22 @@
4465145106
** invoking an external callback, free it now. Calling this function
4465245107
** does not free any Mem.zMalloc buffer.
4465345108
*/
4465445109
SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
4465545110
assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
44656
- if( p->flags&MEM_Agg ){
44657
- sqlite3VdbeMemFinalize(p, p->u.pDef);
44658
- assert( (p->flags & MEM_Agg)==0 );
44659
- sqlite3VdbeMemRelease(p);
44660
- }else if( p->flags&MEM_Dyn && p->xDel ){
44661
- assert( (p->flags&MEM_RowSet)==0 );
44662
- p->xDel((void *)p->z);
44663
- p->xDel = 0;
44664
- }else if( p->flags&MEM_RowSet ){
44665
- sqlite3RowSetClear(p->u.pRowSet);
45111
+ if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet) ){
45112
+ if( p->flags&MEM_Agg ){
45113
+ sqlite3VdbeMemFinalize(p, p->u.pDef);
45114
+ assert( (p->flags & MEM_Agg)==0 );
45115
+ sqlite3VdbeMemRelease(p);
45116
+ }else if( p->flags&MEM_Dyn && p->xDel ){
45117
+ assert( (p->flags&MEM_RowSet)==0 );
45118
+ p->xDel((void *)p->z);
45119
+ p->xDel = 0;
45120
+ }else if( p->flags&MEM_RowSet ){
45121
+ sqlite3RowSetClear(p->u.pRowSet);
45122
+ }
4466645123
}
4466745124
}
4466845125
4466945126
/*
4467045127
** Release any memory held by the Mem. This may leave the Mem in an
@@ -45356,16 +45813,18 @@
4535645813
4535745814
if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
4535845815
zVal = sqlite3DbStrNDup(db, (char*)pExpr->token.z, pExpr->token.n);
4535945816
pVal = sqlite3ValueNew(db);
4536045817
if( !zVal || !pVal ) goto no_mem;
45361
- sqlite3Dequote(zVal);
4536245818
sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
4536345819
if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
45364
- sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, enc);
45820
+ sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
4536545821
}else{
45366
- sqlite3ValueApplyAffinity(pVal, affinity, enc);
45822
+ sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
45823
+ }
45824
+ if( enc!=SQLITE_UTF8 ){
45825
+ sqlite3VdbeChangeEncoding(pVal, enc);
4536745826
}
4536845827
}else if( op==TK_UMINUS ) {
4536945828
if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
4537045829
pVal->u.i = -1 * pVal->u.i;
4537145830
/* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
@@ -45453,11 +45912,11 @@
4545345912
** This file contains code used for creating, destroying, and populating
4545445913
** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
4545545914
** to version 2.8.7, all this code was combined into the vdbe.c source file.
4545645915
** But that file was getting too big so this subroutines were split out.
4545745916
**
45458
-** $Id: vdbeaux.c,v 1.451 2009/04/10 15:42:36 shane Exp $
45917
+** $Id: vdbeaux.c,v 1.457 2009/05/06 18:57:10 shane Exp $
4545945918
*/
4546045919
4546145920
4546245921
4546345922
/*
@@ -46167,13 +46626,13 @@
4616746626
** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
4616846627
**
4616946628
*/
4617046629
SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
4617146630
int mask;
46172
- assert( i>=0 && i<p->db->nDb );
46631
+ assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
4617346632
assert( i<(int)sizeof(p->btreeMask)*8 );
46174
- mask = 1<<i;
46633
+ mask = ((u32)1)<<i;
4617546634
if( (p->btreeMask & mask)==0 ){
4617646635
p->btreeMask |= mask;
4617746636
sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
4617846637
}
4617946638
}
@@ -47377,11 +47836,11 @@
4737747836
*/
4737847837
SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
4737947838
int i;
4738047839
for(i=0; i<pVdbeFunc->nAux; i++){
4738147840
struct AuxData *pAux = &pVdbeFunc->apAux[i];
47382
- if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
47841
+ if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
4738347842
if( pAux->xDelete ){
4738447843
pAux->xDelete(pAux->pAux);
4738547844
}
4738647845
pAux->pAux = 0;
4738747846
}
@@ -47439,12 +47898,12 @@
4743947898
#endif
4744047899
assert( p->isTable );
4744147900
rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
4744247901
if( rc ) return rc;
4744347902
p->lastRowid = keyToInt(p->movetoTarget);
47444
- p->rowidIsValid = res==0 ?1:0;
47445
- if( res<0 ){
47903
+ p->rowidIsValid = ALWAYS(res==0) ?1:0;
47904
+ if( NEVER(res<0) ){
4744647905
rc = sqlite3BtreeNext(p->pCursor, &res);
4744747906
if( rc ) return rc;
4744847907
}
4744947908
#ifdef SQLITE_TEST
4745047909
sqlite3_search_count++;
@@ -47903,10 +48362,11 @@
4790348362
4790448363
pKeyInfo = pPKey2->pKeyInfo;
4790548364
mem1.enc = pKeyInfo->enc;
4790648365
mem1.db = pKeyInfo->db;
4790748366
mem1.flags = 0;
48367
+ mem1.u.i = 0; /* not needed, here to silence compiler warning */
4790848368
mem1.zMalloc = 0;
4790948369
4791048370
idx1 = getVarint32(aKey1, szHdr1);
4791148371
d1 = szHdr1;
4791248372
if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
@@ -47932,10 +48392,22 @@
4793248392
break;
4793348393
}
4793448394
i++;
4793548395
}
4793648396
if( mem1.zMalloc ) sqlite3VdbeMemRelease(&mem1);
48397
+
48398
+ /* If the PREFIX_SEARCH flag is set and all fields except the final
48399
+ ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
48400
+ ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
48401
+ ** This is used by the OP_IsUnique opcode.
48402
+ */
48403
+ if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
48404
+ assert( idx1==szHdr1 && rc );
48405
+ assert( mem1.flags & MEM_Int );
48406
+ pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
48407
+ pPKey2->rowid = mem1.u.i;
48408
+ }
4793748409
4793848410
if( rc==0 ){
4793948411
/* rc==0 here means that one of the keys ran out of fields and
4794048412
** all the fields up to that point were equal. If the UNPACKED_INCRKEY
4794148413
** flag is set, then break the tie by treating key2 as larger.
@@ -48133,11 +48605,11 @@
4813348605
*************************************************************************
4813448606
**
4813548607
** This file contains code use to implement APIs that are part of the
4813648608
** VDBE.
4813748609
**
48138
-** $Id: vdbeapi.c,v 1.161 2009/04/10 23:11:31 drh Exp $
48610
+** $Id: vdbeapi.c,v 1.164 2009/04/27 18:46:06 drh Exp $
4813948611
*/
4814048612
4814148613
#if 0 && defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
4814248614
/*
4814348615
** The following structure contains pointers to the end points of a
@@ -48518,10 +48990,14 @@
4851848990
assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
4851948991
sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
4852048992
}
4852148993
SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
4852248994
pCtx->isError = errCode;
48995
+ if( pCtx->s.flags & MEM_Null ){
48996
+ sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
48997
+ SQLITE_UTF8, SQLITE_STATIC);
48998
+ }
4852348999
}
4852449000
4852549001
/* Force an SQLITE_TOOBIG error. */
4852649002
SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
4852749003
assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
@@ -49270,19 +49746,36 @@
4927049746
return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
4927149747
}
4927249748
#endif /* SQLITE_OMIT_UTF16 */
4927349749
SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
4927449750
int rc;
49275
- Vdbe *p = (Vdbe *)pStmt;
49276
- rc = vdbeUnbind(p, i);
49277
- if( rc==SQLITE_OK ){
49278
- rc = sqlite3VdbeMemCopy(&p->aVar[i-1], pValue);
49279
- if( rc==SQLITE_OK ){
49280
- rc = sqlite3VdbeChangeEncoding(&p->aVar[i-1], ENC(p->db));
49281
- }
49282
- sqlite3_mutex_leave(p->db->mutex);
49283
- rc = sqlite3ApiExit(p->db, rc);
49751
+ switch( pValue->type ){
49752
+ case SQLITE_INTEGER: {
49753
+ rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
49754
+ break;
49755
+ }
49756
+ case SQLITE_FLOAT: {
49757
+ rc = sqlite3_bind_double(pStmt, i, pValue->r);
49758
+ break;
49759
+ }
49760
+ case SQLITE_BLOB: {
49761
+ if( pValue->flags & MEM_Zero ){
49762
+ rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
49763
+ }else{
49764
+ rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
49765
+ }
49766
+ break;
49767
+ }
49768
+ case SQLITE_TEXT: {
49769
+ rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
49770
+ pValue->enc);
49771
+ break;
49772
+ }
49773
+ default: {
49774
+ rc = sqlite3_bind_null(pStmt, i);
49775
+ break;
49776
+ }
4928449777
}
4928549778
return rc;
4928649779
}
4928749780
SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
4928849781
int rc;
@@ -49491,11 +49984,11 @@
4949149984
** documentation, headers files, or other derived files. The formatting
4949249985
** of the code in this file is, therefore, important. See other comments
4949349986
** in this file for details. If in doubt, do not deviate from existing
4949449987
** commenting and indentation practices when changing or adding code.
4949549988
**
49496
-** $Id: vdbe.c,v 1.832 2009/04/10 12:55:17 danielk1977 Exp $
49989
+** $Id: vdbe.c,v 1.842 2009/05/06 18:57:10 shane Exp $
4949749990
*/
4949849991
4949949992
/*
4950049993
** The following global variable is incremented every time a cursor
4950149994
** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
@@ -49874,10 +50367,12 @@
4987450367
fprintf(out, " si:%lld", p->u.i);
4987550368
}else if( p->flags & MEM_Int ){
4987650369
fprintf(out, " i:%lld", p->u.i);
4987750370
}else if( p->flags & MEM_Real ){
4987850371
fprintf(out, " r:%g", p->r);
50372
+ }else if( p->flags & MEM_RowSet ){
50373
+ fprintf(out, " (rowset)");
4987950374
}else{
4988050375
char zBuf[200];
4988150376
sqlite3VdbeMemPrettyPrint(p, zBuf);
4988250377
fprintf(out, " ");
4988350378
fprintf(out, "%s", zBuf);
@@ -51999,11 +52494,11 @@
5199952494
if( db->autoCommit ){
5200052495
db->autoCommit = 0;
5200152496
db->isTransactionSavepoint = 1;
5200252497
}else{
5200352498
db->nSavepoint++;
52004
- }
52499
+ }
5200552500
5200652501
/* Link the new savepoint into the database handle's list. */
5200752502
pNew->pNext = db->pSavepoint;
5200852503
db->pSavepoint = pNew;
5200952504
}
@@ -52873,107 +53368,86 @@
5287353368
break;
5287453369
}
5287553370
5287653371
/* Opcode: IsUnique P1 P2 P3 P4 *
5287753372
**
52878
-** The P3 register contains an integer record number. Call this
52879
-** record number R. The P4 register contains an index key created
52880
-** using MakeRecord. Call it K.
52881
-**
52882
-** P1 is an index. So it has no data and its key consists of a
52883
-** record generated by OP_MakeRecord where the last field is the
53373
+** Cursor P1 is open on an index. So it has no data and its key consists
53374
+** of a record generated by OP_MakeRecord where the last field is the
5288453375
** rowid of the entry that the index refers to.
52885
-**
52886
-** This instruction asks if there is an entry in P1 where the
52887
-** fields matches K but the rowid is different from R.
52888
-** If there is no such entry, then there is an immediate
52889
-** jump to P2. If any entry does exist where the index string
52890
-** matches K but the record number is not R, then the record
52891
-** number for that entry is written into P3 and control
52892
-** falls through to the next instruction.
53376
+**
53377
+** The P3 register contains an integer record number. Call this record
53378
+** number R. Register P4 is the first in a set of N contiguous registers
53379
+** that make up an unpacked index key that can be used with cursor P1.
53380
+** The value of N can be inferred from the cursor. N includes the rowid
53381
+** value appended to the end of the index record. This rowid value may
53382
+** or may not be the same as R.
53383
+**
53384
+** If any of the N registers beginning with register P4 contains a NULL
53385
+** value, jump immediately to P2.
53386
+**
53387
+** Otherwise, this instruction checks if cursor P1 contains an entry
53388
+** where the first (N-1) fields match but the rowid value at the end
53389
+** of the index entry is not R. If there is no such entry, control jumps
53390
+** to instruction P2. Otherwise, the rowid of the conflicting index
53391
+** entry is copied to register P3 and control falls through to the next
53392
+** instruction.
5289353393
**
5289453394
** See also: NotFound, NotExists, Found
5289553395
*/
5289653396
case OP_IsUnique: { /* jump, in3 */
52897
- int i = pOp->p1;
53397
+ u16 ii;
5289853398
VdbeCursor *pCx;
5289953399
BtCursor *pCrsr;
52900
- Mem *pK;
52901
- i64 R;
53400
+ u16 nField;
53401
+ Mem *aMem = &p->aMem[pOp->p4.i];
5290253402
52903
- /* Pop the value R off the top of the stack
52904
- */
53403
+ /* Assert that the values of parameters P1 and P4 are in range. */
5290553404
assert( pOp->p4type==P4_INT32 );
5290653405
assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
52907
- pK = &p->aMem[pOp->p4.i];
52908
- sqlite3VdbeMemIntegerify(pIn3);
52909
- R = pIn3->u.i;
52910
- assert( i>=0 && i<p->nCursor );
52911
- pCx = p->apCsr[i];
52912
- assert( pCx!=0 );
52913
- pCrsr = pCx->pCursor;
52914
- if( pCrsr!=0 ){
52915
- int res;
52916
- i64 v; /* The record number that matches K */
52917
- UnpackedRecord *pIdxKey; /* Unpacked version of P4 */
52918
-
52919
- /* Make sure K is a string and make zKey point to K
52920
- */
52921
- assert( pK->flags & MEM_Blob );
52922
- pIdxKey = sqlite3VdbeRecordUnpack(pCx->pKeyInfo, pK->n, pK->z,
52923
- aTempRec, sizeof(aTempRec));
52924
- if( pIdxKey==0 ){
52925
- goto no_mem;
52926
- }
52927
- pIdxKey->flags |= UNPACKED_IGNORE_ROWID;
52928
-
52929
- /* Search for an entry in P1 where all but the last rowid match K
52930
- ** If there is no such entry, jump immediately to P2.
52931
- */
52932
- assert( pCx->deferredMoveto==0 );
52933
- pCx->cacheStatus = CACHE_STALE;
52934
- rc = sqlite3BtreeMovetoUnpacked(pCrsr, pIdxKey, 0, 0, &res);
52935
- if( rc!=SQLITE_OK ){
52936
- sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
52937
- goto abort_due_to_error;
52938
- }
52939
- if( res<0 ){
52940
- rc = sqlite3BtreeNext(pCrsr, &res);
52941
- if( res ){
52942
- pc = pOp->p2 - 1;
52943
- sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
52944
- break;
52945
- }
52946
- }
52947
- rc = sqlite3VdbeIdxKeyCompare(pCx, pIdxKey, &res);
52948
- sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
52949
- if( rc!=SQLITE_OK ) goto abort_due_to_error;
52950
- if( res>0 ){
52951
- pc = pOp->p2 - 1;
52952
- break;
52953
- }
52954
-
52955
- /* At this point, pCrsr is pointing to an entry in P1 where all but
52956
- ** the final entry (the rowid) matches K. Check to see if the
52957
- ** final rowid column is different from R. If it equals R then jump
52958
- ** immediately to P2.
52959
- */
52960
- rc = sqlite3VdbeIdxRowid(pCrsr, &v);
52961
- if( rc!=SQLITE_OK ){
52962
- goto abort_due_to_error;
52963
- }
52964
- if( v==R ){
52965
- pc = pOp->p2 - 1;
52966
- break;
52967
- }
52968
-
52969
- /* The final varint of the key is different from R. Store it back
52970
- ** into register R3. (The record number of an entry that violates
52971
- ** a UNIQUE constraint.)
52972
- */
52973
- pIn3->u.i = v;
52974
- assert( pIn3->flags&MEM_Int );
53406
+ assert( pOp->p1>=0 && pOp->p1<p->nCursor );
53407
+
53408
+ /* Find the index cursor. */
53409
+ pCx = p->apCsr[pOp->p1];
53410
+ assert( pCx->deferredMoveto==0 );
53411
+ pCx->seekResult = 0;
53412
+ pCx->cacheStatus = CACHE_STALE;
53413
+ pCrsr = pCx->pCursor;
53414
+
53415
+ /* If any of the values are NULL, take the jump. */
53416
+ nField = pCx->pKeyInfo->nField;
53417
+ for(ii=0; ii<nField; ii++){
53418
+ if( aMem[ii].flags & MEM_Null ){
53419
+ pc = pOp->p2 - 1;
53420
+ pCrsr = 0;
53421
+ break;
53422
+ }
53423
+ }
53424
+ assert( (aMem[nField].flags & MEM_Null)==0 );
53425
+
53426
+ if( pCrsr!=0 ){
53427
+ UnpackedRecord r; /* B-Tree index search key */
53428
+ i64 R; /* Rowid stored in register P3 */
53429
+
53430
+ /* Populate the index search key. */
53431
+ r.pKeyInfo = pCx->pKeyInfo;
53432
+ r.nField = nField + 1;
53433
+ r.flags = UNPACKED_PREFIX_SEARCH;
53434
+ r.aMem = aMem;
53435
+
53436
+ /* Extract the value of R from register P3. */
53437
+ sqlite3VdbeMemIntegerify(pIn3);
53438
+ R = pIn3->u.i;
53439
+
53440
+ /* Search the B-Tree index. If no conflicting record is found, jump
53441
+ ** to P2. Otherwise, copy the rowid of the conflicting record to
53442
+ ** register P3 and fall through to the next instruction. */
53443
+ rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &pCx->seekResult);
53444
+ if( (r.flags & UNPACKED_PREFIX_SEARCH) || r.rowid==R ){
53445
+ pc = pOp->p2 - 1;
53446
+ }else{
53447
+ pIn3->u.i = r.rowid;
53448
+ }
5297553449
}
5297653450
break;
5297753451
}
5297853452
5297953453
/* Opcode: NotExists P1 P2 P3 * *
@@ -53000,26 +53474,29 @@
5300053474
int res = 0;
5300153475
u64 iKey;
5300253476
assert( pIn3->flags & MEM_Int );
5300353477
assert( p->apCsr[i]->isTable );
5300453478
iKey = intToKey(pIn3->u.i);
53005
- rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0,&res);
53479
+ rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
5300653480
pC->lastRowid = pIn3->u.i;
5300753481
pC->rowidIsValid = res==0 ?1:0;
5300853482
pC->nullRow = 0;
5300953483
pC->cacheStatus = CACHE_STALE;
53484
+ pC->deferredMoveto = 0;
5301053485
if( res!=0 ){
5301153486
pc = pOp->p2 - 1;
5301253487
assert( pC->rowidIsValid==0 );
5301353488
}
53489
+ pC->seekResult = res;
5301453490
}else if( !pC->pseudoTable ){
5301553491
/* This happens when an attempt to open a read cursor on the
5301653492
** sqlite_master table returns SQLITE_EMPTY.
5301753493
*/
5301853494
assert( pC->isTable );
5301953495
pc = pOp->p2 - 1;
5302053496
assert( pC->rowidIsValid==0 );
53497
+ pC->seekResult = 0;
5302153498
}
5302253499
break;
5302353500
}
5302453501
5302553502
/* Opcode: Sequence P1 P2 * * *
@@ -53258,19 +53735,21 @@
5325853735
pC->pData[pC->nData+1] = 0;
5325953736
}
5326053737
pC->nullRow = 0;
5326153738
}else{
5326253739
int nZero;
53740
+ int seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
5326353741
if( pData->flags & MEM_Zero ){
5326453742
nZero = pData->u.nZero;
5326553743
}else{
5326653744
nZero = 0;
5326753745
}
5326853746
sqlite3BtreeSetCachedRowid(pC->pCursor, 0);
5326953747
rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
5327053748
pData->z, pData->n, nZero,
53271
- pOp->p5 & OPFLAG_APPEND);
53749
+ pOp->p5 & OPFLAG_APPEND, seekResult
53750
+ );
5327253751
}
5327353752
5327453753
pC->rowidIsValid = 0;
5327553754
pC->deferredMoveto = 0;
5327653755
pC->cacheStatus = CACHE_STALE;
@@ -53430,32 +53909,54 @@
5343053909
5343153910
/* Opcode: Rowid P1 P2 * * *
5343253911
**
5343353912
** Store in register P2 an integer which is the key of the table entry that
5343453913
** P1 is currently point to.
53914
+**
53915
+** P1 can be either an ordinary table or a virtual table. There used to
53916
+** be a separate OP_VRowid opcode for use with virtual tables, but this
53917
+** one opcode now works for both table types.
5343553918
*/
5343653919
case OP_Rowid: { /* out2-prerelease */
5343753920
int i = pOp->p1;
5343853921
VdbeCursor *pC;
5343953922
i64 v;
5344053923
5344153924
assert( i>=0 && i<p->nCursor );
5344253925
pC = p->apCsr[i];
5344353926
assert( pC!=0 );
53444
- rc = sqlite3VdbeCursorMoveto(pC);
53445
- if( rc ) goto abort_due_to_error;
53446
- if( pC->rowidIsValid ){
53447
- v = pC->lastRowid;
53927
+ if( pC->nullRow ){
53928
+ /* Do nothing so that reg[P2] remains NULL */
53929
+ break;
53930
+ }else if( pC->deferredMoveto ){
53931
+ v = pC->movetoTarget;
5344853932
}else if( pC->pseudoTable ){
5344953933
v = keyToInt(pC->iKey);
53450
- }else if( pC->nullRow ){
53451
- /* Leave the rowid set to a NULL */
53452
- break;
53934
+#ifndef SQLITE_OMIT_VIRTUALTABLE
53935
+ }else if( pC->pVtabCursor ){
53936
+ sqlite3_vtab *pVtab;
53937
+ const sqlite3_module *pModule;
53938
+ pVtab = pC->pVtabCursor->pVtab;
53939
+ pModule = pVtab->pModule;
53940
+ assert( pModule->xRowid );
53941
+ if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
53942
+ rc = pModule->xRowid(pC->pVtabCursor, &v);
53943
+ sqlite3DbFree(db, p->zErrMsg);
53944
+ p->zErrMsg = pVtab->zErrMsg;
53945
+ pVtab->zErrMsg = 0;
53946
+ if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
53947
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
5345353948
}else{
53454
- assert( pC->pCursor!=0 );
53455
- sqlite3BtreeKeySize(pC->pCursor, &v);
53456
- v = keyToInt(v);
53949
+ rc = sqlite3VdbeCursorMoveto(pC);
53950
+ if( rc ) goto abort_due_to_error;
53951
+ if( pC->rowidIsValid ){
53952
+ v = pC->lastRowid;
53953
+ }else{
53954
+ assert( pC->pCursor!=0 );
53955
+ sqlite3BtreeKeySize(pC->pCursor, &v);
53956
+ v = keyToInt(v);
53957
+ }
5345753958
}
5345853959
pOut->u.i = v;
5345953960
MemSetTypeFlag(pOut, MEM_Int);
5346053961
break;
5346153962
}
@@ -53615,11 +54116,11 @@
5361554116
}
5361654117
pC->rowidIsValid = 0;
5361754118
break;
5361854119
}
5361954120
53620
-/* Opcode: IdxInsert P1 P2 P3 * *
54121
+/* Opcode: IdxInsert P1 P2 P3 * P5
5362154122
**
5362254123
** Register P2 holds a SQL index key made using the
5362354124
** MakeRecord instructions. This opcode writes that key
5362454125
** into the index P1. Data for the entry is nil.
5362554126
**
@@ -53640,11 +54141,13 @@
5364054141
assert( pC->isTable==0 );
5364154142
rc = ExpandBlob(pIn2);
5364254143
if( rc==SQLITE_OK ){
5364354144
int nKey = pIn2->n;
5364454145
const char *zKey = pIn2->z;
53645
- rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3);
54146
+ rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3,
54147
+ ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
54148
+ );
5364654149
assert( pC->deferredMoveto==0 );
5364754150
pC->cacheStatus = CACHE_STALE;
5364854151
}
5364954152
}
5365054153
break;
@@ -54138,10 +54641,63 @@
5413854641
sqlite3VdbeMemSetInt64(pOut, val);
5413954642
}
5414054643
break;
5414154644
}
5414254645
54646
+/* Opcode: RowSetTest P1 P2 P3 P4
54647
+**
54648
+** Register P3 is assumed to hold a 64-bit integer value. If register P1
54649
+** contains a RowSet object and that RowSet object contains
54650
+** the value held in P3, jump to register P2. Otherwise, insert the
54651
+** integer in P3 into the RowSet and continue on to the
54652
+** next opcode.
54653
+**
54654
+** The RowSet object is optimized for the case where successive sets
54655
+** of integers, where each set contains no duplicates. Each set
54656
+** of values is identified by a unique P4 value. The first set
54657
+** must have P4==0, the final set P4=-1. P4 must be either -1 or
54658
+** non-negative. For non-negative values of P4 only the lower 4
54659
+** bits are significant.
54660
+**
54661
+** This allows optimizations: (a) when P4==0 there is no need to test
54662
+** the rowset object for P3, as it is guaranteed not to contain it,
54663
+** (b) when P4==-1 there is no need to insert the value, as it will
54664
+** never be tested for, and (c) when a value that is part of set X is
54665
+** inserted, there is no need to search to see if the same value was
54666
+** previously inserted as part of set X (only if it was previously
54667
+** inserted as part of some other set).
54668
+*/
54669
+case OP_RowSetTest: { /* jump, in1, in3 */
54670
+ int iSet = pOp->p4.i;
54671
+ assert( pIn3->flags&MEM_Int );
54672
+
54673
+ /* If there is anything other than a rowset object in memory cell P1,
54674
+ ** delete it now and initialize P1 with an empty rowset
54675
+ */
54676
+ if( (pIn1->flags & MEM_RowSet)==0 ){
54677
+ sqlite3VdbeMemSetRowSet(pIn1);
54678
+ if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
54679
+ }
54680
+
54681
+ assert( pOp->p4type==P4_INT32 );
54682
+ assert( iSet==-1 || iSet>=0 );
54683
+ if( iSet ){
54684
+ int exists;
54685
+ exists = sqlite3RowSetTest(pIn1->u.pRowSet,
54686
+ (u8)(iSet>=0 ? iSet & 0xf : 0xff),
54687
+ pIn3->u.i);
54688
+ if( exists ){
54689
+ pc = pOp->p2 - 1;
54690
+ break;
54691
+ }
54692
+ }
54693
+ if( iSet>=0 ){
54694
+ sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
54695
+ }
54696
+ break;
54697
+}
54698
+
5414354699
5414454700
#ifndef SQLITE_OMIT_TRIGGER
5414554701
/* Opcode: ContextPush * * *
5414654702
**
5414754703
** Save the current Vdbe context such that it can be restored by a ContextPop
@@ -54569,41 +55125,10 @@
5456955125
}
5457055126
pCur->nullRow = 0;
5457155127
5457255128
break;
5457355129
}
54574
-#endif /* SQLITE_OMIT_VIRTUALTABLE */
54575
-
54576
-#ifndef SQLITE_OMIT_VIRTUALTABLE
54577
-/* Opcode: VRowid P1 P2 * * *
54578
-**
54579
-** Store into register P2 the rowid of
54580
-** the virtual-table that the P1 cursor is pointing to.
54581
-*/
54582
-case OP_VRowid: { /* out2-prerelease */
54583
- sqlite3_vtab *pVtab;
54584
- const sqlite3_module *pModule;
54585
- sqlite_int64 iRow;
54586
- VdbeCursor *pCur = p->apCsr[pOp->p1];
54587
-
54588
- assert( pCur->pVtabCursor );
54589
- if( pCur->nullRow ){
54590
- break;
54591
- }
54592
- pVtab = pCur->pVtabCursor->pVtab;
54593
- pModule = pVtab->pModule;
54594
- assert( pModule->xRowid );
54595
- if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
54596
- rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
54597
- sqlite3DbFree(db, p->zErrMsg);
54598
- p->zErrMsg = pVtab->zErrMsg;
54599
- pVtab->zErrMsg = 0;
54600
- if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
54601
- MemSetTypeFlag(pOut, MEM_Int);
54602
- pOut->u.i = iRow;
54603
- break;
54604
-}
5460555130
#endif /* SQLITE_OMIT_VIRTUALTABLE */
5460655131
5460755132
#ifndef SQLITE_OMIT_VIRTUALTABLE
5460855133
/* Opcode: VColumn P1 P2 P3 * *
5460955134
**
@@ -55569,11 +56094,11 @@
5556956094
**
5557056095
** This file contains code use to implement an in-memory rollback journal.
5557156096
** The in-memory rollback journal is used to journal transactions for
5557256097
** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
5557356098
**
55574
-** @(#) $Id: memjournal.c,v 1.11 2009/04/05 12:22:09 drh Exp $
56099
+** @(#) $Id: memjournal.c,v 1.12 2009/05/04 11:42:30 danielk1977 Exp $
5557556100
*/
5557656101
5557756102
/* Forward references to internal structures */
5557856103
typedef struct MemJournal MemJournal;
5557956104
typedef struct FilePoint FilePoint;
@@ -55683,11 +56208,11 @@
5568356208
u8 *zWrite = (u8 *)zBuf;
5568456209
5568556210
/* An in-memory journal file should only ever be appended to. Random
5568656211
** access writes are not required by sqlite.
5568756212
*/
55688
- assert(iOfst==p->endpoint.iOffset);
56213
+ assert( iOfst==p->endpoint.iOffset );
5568956214
UNUSED_PARAMETER(iOfst);
5569056215
5569156216
while( nWrite>0 ){
5569256217
FileChunk *pChunk = p->endpoint.pChunk;
5569356218
int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
@@ -55969,11 +56494,11 @@
5596956494
**
5597056495
** This file contains routines used for walking the parser tree and
5597156496
** resolve all identifiers by associating them with a particular
5597256497
** table and column.
5597356498
**
55974
-** $Id: resolve.c,v 1.20 2009/03/05 04:23:47 shane Exp $
56499
+** $Id: resolve.c,v 1.22 2009/05/05 15:46:43 drh Exp $
5597556500
*/
5597656501
5597756502
/*
5597856503
** Turn the pExpr expression into an alias for the iCol-th column of the
5597956504
** result set in pEList.
@@ -56200,11 +56725,15 @@
5620056725
pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
5620156726
pExpr->pTab = pTab;
5620256727
if( iCol>=0 ){
5620356728
testcase( iCol==31 );
5620456729
testcase( iCol==32 );
56205
- *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0);
56730
+ if( iCol>=32 ){
56731
+ *piColMask = 0xffffffff;
56732
+ }else{
56733
+ *piColMask |= ((u32)1)<<iCol;
56734
+ }
5620656735
}
5620756736
break;
5620856737
}
5620956738
}
5621056739
}
@@ -56271,11 +56800,11 @@
5627156800
** pExpr.
5627256801
**
5627356802
** Because no reference was made to outer contexts, the pNC->nRef
5627456803
** fields are not changed in any context.
5627556804
*/
56276
- if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
56805
+ if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
5627756806
sqlite3DbFree(db, zCol);
5627856807
pExpr->op = TK_STRING;
5627956808
pExpr->pTab = 0;
5628056809
return 0;
5628156810
}
@@ -57139,11 +57668,11 @@
5713957668
**
5714057669
*************************************************************************
5714157670
** This file contains routines used for analyzing expressions and
5714257671
** for generating VDBE code that evaluates expressions in SQLite.
5714357672
**
57144
-** $Id: expr.c,v 1.426 2009/04/08 13:51:51 drh Exp $
57673
+** $Id: expr.c,v 1.432 2009/05/06 18:57:10 shane Exp $
5714557674
*/
5714657675
5714757676
/*
5714857677
** Return the 'affinity' of the expression pExpr if any.
5714957678
**
@@ -57533,25 +58062,22 @@
5753358062
pNew->span.z = (u8*)"";
5753458063
if( pToken ){
5753558064
int c;
5753658065
assert( pToken->dyn==0 );
5753758066
pNew->span = *pToken;
57538
-
57539
- /* The pToken->z value is read-only. But the new expression
57540
- ** node created here might be passed to sqlite3DequoteExpr() which
57541
- ** will attempt to modify pNew->token.z. Hence, if the token
57542
- ** is quoted, make a copy now so that DequoteExpr() will change
57543
- ** the copy rather than the original text.
57544
- */
5754558067
if( pToken->n>=2
5754658068
&& ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
5754758069
sqlite3TokenCopy(db, &pNew->token, pToken);
58070
+ if( pNew->token.z ){
58071
+ pNew->token.n = sqlite3Dequote((char*)pNew->token.z);
58072
+ assert( pNew->token.n==(unsigned)sqlite3Strlen30((char*)pNew->token.z) );
58073
+ }
58074
+ if( c=='"' ) pNew->flags |= EP_DblQuoted;
5754858075
}else{
5754958076
pNew->token = *pToken;
57550
- pNew->flags |= EP_Dequoted;
57551
- VVA_ONLY( pNew->vvaFlags |= EVVA_ReadOnlyToken; )
5755258077
}
58078
+ pNew->token.quoted = 0;
5755358079
}else if( pLeft ){
5755458080
if( pRight ){
5755558081
if( pRight->span.dyn==0 && pLeft->span.dyn==0 ){
5755658082
sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
5755758083
}
@@ -57784,22 +58310,10 @@
5778458310
if( p==0 ) return;
5778558311
sqlite3ExprClear(db, p);
5778658312
sqlite3DbFree(db, p);
5778758313
}
5778858314
57789
-/*
57790
-** The Expr.token field might be a string literal that is quoted.
57791
-** If so, remove the quotation marks.
57792
-*/
57793
-SQLITE_PRIVATE void sqlite3DequoteExpr(Expr *p){
57794
- if( !ExprHasAnyProperty(p, EP_Dequoted) ){
57795
- ExprSetProperty(p, EP_Dequoted);
57796
- assert( (p->vvaFlags & EVVA_ReadOnlyToken)==0 );
57797
- sqlite3Dequote((char*)p->token.z);
57798
- }
57799
-}
57800
-
5780158315
/*
5780258316
** Return the number of bytes allocated for the expression structure
5780358317
** passed as the first argument. This is always one of EXPR_FULLSIZE,
5780458318
** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
5780558319
*/
@@ -58589,11 +59103,11 @@
5858959103
int isRowid
5859059104
){
5859159105
int testAddr = 0; /* One-time test address */
5859259106
Vdbe *v = sqlite3GetVdbe(pParse);
5859359107
if( v==0 ) return;
58594
-
59108
+ sqlite3ExprCachePush(pParse);
5859559109
5859659110
/* This code must be run in its entirety every time it is encountered
5859759111
** if any of the following is true:
5859859112
**
5859959113
** * The right-hand side is a correlated subquery
@@ -58696,15 +59210,11 @@
5869659210
sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
5869759211
testAddr = 0;
5869859212
}
5869959213
5870059214
/* Evaluate the expression and insert it into the temp table */
58701
- pParse->disableColCache++;
5870259215
r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
58703
- assert( pParse->disableColCache>0 );
58704
- pParse->disableColCache--;
58705
-
5870659216
if( isRowid ){
5870759217
sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, sqlite3VdbeCurrentAddr(v)+2);
5870859218
sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
5870959219
}else{
5871059220
sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
@@ -58725,11 +59235,11 @@
5872559235
case TK_SELECT: {
5872659236
/* This has to be a scalar SELECT. Generate code to put the
5872759237
** value of this select in a memory cell and record the number
5872859238
** of the memory cell in iColumn.
5872959239
*/
58730
- static const Token one = { (u8*)"1", 0, 1 };
59240
+ static const Token one = { (u8*)"1", 0, 0, 1 };
5873159241
Select *pSel;
5873259242
SelectDest dest;
5873359243
5873459244
assert( ExprHasProperty(pExpr, EP_xIsSelect) );
5873559245
pSel = pExpr->x.pSelect;
@@ -58754,10 +59264,11 @@
5875459264
}
5875559265
5875659266
if( testAddr ){
5875759267
sqlite3VdbeJumpHere(v, testAddr-1);
5875859268
}
59269
+ sqlite3ExprCachePop(pParse, 1);
5875959270
5876059271
return;
5876159272
}
5876259273
#endif /* SQLITE_OMIT_SUBQUERY */
5876359274
@@ -58831,10 +59342,124 @@
5883159342
codeReal(v, z, n, negFlag, iMem);
5883259343
}
5883359344
}
5883459345
}
5883559346
59347
+/*
59348
+** Clear a cache entry.
59349
+*/
59350
+static void cacheEntryClear(Parse *pParse, struct yColCache *p){
59351
+ if( p->tempReg ){
59352
+ if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
59353
+ pParse->aTempReg[pParse->nTempReg++] = p->iReg;
59354
+ }
59355
+ p->tempReg = 0;
59356
+ }
59357
+}
59358
+
59359
+
59360
+/*
59361
+** Record in the column cache that a particular column from a
59362
+** particular table is stored in a particular register.
59363
+*/
59364
+SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
59365
+ int i;
59366
+ int minLru;
59367
+ int idxLru;
59368
+ struct yColCache *p;
59369
+
59370
+ /* First replace any existing entry */
59371
+ for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59372
+ if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
59373
+ cacheEntryClear(pParse, p);
59374
+ p->iLevel = pParse->iCacheLevel;
59375
+ p->iReg = iReg;
59376
+ p->affChange = 0;
59377
+ p->lru = pParse->iCacheCnt++;
59378
+ return;
59379
+ }
59380
+ }
59381
+ if( iReg<=0 ) return;
59382
+
59383
+ /* Find an empty slot and replace it */
59384
+ for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59385
+ if( p->iReg==0 ){
59386
+ p->iLevel = pParse->iCacheLevel;
59387
+ p->iTable = iTab;
59388
+ p->iColumn = iCol;
59389
+ p->iReg = iReg;
59390
+ p->affChange = 0;
59391
+ p->tempReg = 0;
59392
+ p->lru = pParse->iCacheCnt++;
59393
+ return;
59394
+ }
59395
+ }
59396
+
59397
+ /* Replace the last recently used */
59398
+ minLru = 0x7fffffff;
59399
+ idxLru = -1;
59400
+ for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59401
+ if( p->lru<minLru ){
59402
+ idxLru = i;
59403
+ minLru = p->lru;
59404
+ }
59405
+ }
59406
+ if( idxLru>=0 ){
59407
+ p = &pParse->aColCache[idxLru];
59408
+ p->iLevel = pParse->iCacheLevel;
59409
+ p->iTable = iTab;
59410
+ p->iColumn = iCol;
59411
+ p->iReg = iReg;
59412
+ p->affChange = 0;
59413
+ p->tempReg = 0;
59414
+ p->lru = pParse->iCacheCnt++;
59415
+ return;
59416
+ }
59417
+}
59418
+
59419
+/*
59420
+** Indicate that a register is being overwritten. Purge the register
59421
+** from the column cache.
59422
+*/
59423
+SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg){
59424
+ int i;
59425
+ struct yColCache *p;
59426
+ for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59427
+ if( p->iReg==iReg ){
59428
+ cacheEntryClear(pParse, p);
59429
+ p->iReg = 0;
59430
+ }
59431
+ }
59432
+}
59433
+
59434
+/*
59435
+** Remember the current column cache context. Any new entries added
59436
+** added to the column cache after this call are removed when the
59437
+** corresponding pop occurs.
59438
+*/
59439
+SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
59440
+ pParse->iCacheLevel++;
59441
+}
59442
+
59443
+/*
59444
+** Remove from the column cache any entries that were added since the
59445
+** the previous N Push operations. In other words, restore the cache
59446
+** to the state it was in N Pushes ago.
59447
+*/
59448
+SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
59449
+ int i;
59450
+ struct yColCache *p;
59451
+ assert( N>0 );
59452
+ assert( pParse->iCacheLevel>=N );
59453
+ pParse->iCacheLevel -= N;
59454
+ for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59455
+ if( p->iReg && p->iLevel>pParse->iCacheLevel ){
59456
+ cacheEntryClear(pParse, p);
59457
+ p->iReg = 0;
59458
+ }
59459
+ }
59460
+}
5883659461
5883759462
/*
5883859463
** Generate code that will extract the iColumn-th column from
5883959464
** table pTab and store the column value in a register. An effort
5884059465
** is made to store the column value in register iReg, but this is
@@ -58859,24 +59484,25 @@
5885959484
){
5886059485
Vdbe *v = pParse->pVdbe;
5886159486
int i;
5886259487
struct yColCache *p;
5886359488
58864
- for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
58865
- if( p->iTable==iTable && p->iColumn==iColumn
59489
+ for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59490
+ if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn
5886659491
&& (!p->affChange || allowAffChng) ){
5886759492
#if 0
5886859493
sqlite3VdbeAddOp0(v, OP_Noop);
5886959494
VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
5887059495
#endif
59496
+ p->lru = pParse->iCacheCnt++;
59497
+ p->tempReg = 0; /* This pins the register, but also leaks it */
5887159498
return p->iReg;
5887259499
}
5887359500
}
5887459501
assert( v!=0 );
5887559502
if( iColumn<0 ){
58876
- int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
58877
- sqlite3VdbeAddOp2(v, op, iTable, iReg);
59503
+ sqlite3VdbeAddOp2(v, OP_Rowid, iTable, iReg);
5887859504
}else if( pTab==0 ){
5887959505
sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
5888059506
}else{
5888159507
int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
5888259508
sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
@@ -58885,41 +59511,25 @@
5888559511
if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
5888659512
sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
5888759513
}
5888859514
#endif
5888959515
}
58890
- if( pParse->disableColCache==0 ){
58891
- i = pParse->iColCache;
58892
- p = &pParse->aColCache[i];
58893
- p->iTable = iTable;
58894
- p->iColumn = iColumn;
58895
- p->iReg = iReg;
58896
- p->affChange = 0;
58897
- i++;
58898
- if( i>=ArraySize(pParse->aColCache) ) i = 0;
58899
- if( i>pParse->nColCache ) pParse->nColCache = i;
58900
- pParse->iColCache = i;
58901
- }
59516
+ sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
5890259517
return iReg;
5890359518
}
5890459519
5890559520
/*
58906
-** Clear all column cache entries associated with the vdbe
58907
-** cursor with cursor number iTable.
59521
+** Clear all column cache entries.
5890859522
*/
58909
-SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){
58910
- if( iTable<0 ){
58911
- pParse->nColCache = 0;
58912
- pParse->iColCache = 0;
58913
- }else{
58914
- int i;
58915
- for(i=0; i<pParse->nColCache; i++){
58916
- if( pParse->aColCache[i].iTable==iTable ){
58917
- testcase( i==pParse->nColCache-1 );
58918
- pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
58919
- pParse->iColCache = pParse->nColCache;
58920
- }
59523
+SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
59524
+ int i;
59525
+ struct yColCache *p;
59526
+
59527
+ for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59528
+ if( p->iReg ){
59529
+ cacheEntryClear(pParse, p);
59530
+ p->iReg = 0;
5892159531
}
5892259532
}
5892359533
}
5892459534
5892559535
/*
@@ -58927,14 +59537,15 @@
5892759537
** registers starting with iStart.
5892859538
*/
5892959539
SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
5893059540
int iEnd = iStart + iCount - 1;
5893159541
int i;
58932
- for(i=0; i<pParse->nColCache; i++){
58933
- int r = pParse->aColCache[i].iReg;
59542
+ struct yColCache *p;
59543
+ for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59544
+ int r = p->iReg;
5893459545
if( r>=iStart && r<=iEnd ){
58935
- pParse->aColCache[i].affChange = 1;
59546
+ p->affChange = 1;
5893659547
}
5893759548
}
5893859549
}
5893959550
5894059551
/*
@@ -58941,16 +59552,17 @@
5894159552
** Generate code to move content from registers iFrom...iFrom+nReg-1
5894259553
** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
5894359554
*/
5894459555
SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
5894559556
int i;
59557
+ struct yColCache *p;
5894659558
if( iFrom==iTo ) return;
5894759559
sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
58948
- for(i=0; i<pParse->nColCache; i++){
58949
- int x = pParse->aColCache[i].iReg;
59560
+ for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59561
+ int x = p->iReg;
5895059562
if( x>=iFrom && x<iFrom+nReg ){
58951
- pParse->aColCache[i].iReg += iTo-iFrom;
59563
+ p->iReg += iTo-iFrom;
5895259564
}
5895359565
}
5895459566
}
5895559567
5895659568
/*
@@ -58969,36 +59581,18 @@
5896959581
** Return true if any register in the range iFrom..iTo (inclusive)
5897059582
** is used as part of the column cache.
5897159583
*/
5897259584
static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
5897359585
int i;
58974
- for(i=0; i<pParse->nColCache; i++){
58975
- int r = pParse->aColCache[i].iReg;
59586
+ struct yColCache *p;
59587
+ for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59588
+ int r = p->iReg;
5897659589
if( r>=iFrom && r<=iTo ) return 1;
5897759590
}
5897859591
return 0;
5897959592
}
5898059593
58981
-/*
58982
-** There is a value in register iReg.
58983
-**
58984
-** We are going to modify the value, so we need to make sure it
58985
-** is not a cached register. If iReg is a cached register,
58986
-** then clear the corresponding cache line.
58987
-*/
58988
-SQLITE_PRIVATE void sqlite3ExprWritableRegister(Parse *pParse, int iReg){
58989
- int i;
58990
- if( usedAsColumnCache(pParse, iReg, iReg) ){
58991
- for(i=0; i<pParse->nColCache; i++){
58992
- if( pParse->aColCache[i].iReg==iReg ){
58993
- pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
58994
- pParse->iColCache = pParse->nColCache;
58995
- }
58996
- }
58997
- }
58998
-}
58999
-
5900059594
/*
5900159595
** If the last instruction coded is an ephemeral copy of any of
5900259596
** the registers in the nReg registers beginning with iReg, then
5900359597
** convert the last instruction from OP_SCopy to OP_Copy.
5900459598
*/
@@ -59032,10 +59626,11 @@
5903259626
** pParse->aAlias[iAlias-1] records the register number where the value
5903359627
** of the iAlias-th alias is stored. If zero, that means that the
5903459628
** alias has not yet been computed.
5903559629
*/
5903659630
static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
59631
+#if 0
5903759632
sqlite3 *db = pParse->db;
5903859633
int iReg;
5903959634
if( pParse->nAliasAlloc<pParse->nAlias ){
5904059635
pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
5904159636
sizeof(pParse->aAlias[0])*pParse->nAlias );
@@ -59046,19 +59641,23 @@
5904659641
pParse->nAliasAlloc = pParse->nAlias;
5904759642
}
5904859643
assert( iAlias>0 && iAlias<=pParse->nAlias );
5904959644
iReg = pParse->aAlias[iAlias-1];
5905059645
if( iReg==0 ){
59051
- if( pParse->disableColCache ){
59646
+ if( pParse->iCacheLevel>0 ){
5905259647
iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
5905359648
}else{
5905459649
iReg = ++pParse->nMem;
5905559650
sqlite3ExprCode(pParse, pExpr, iReg);
5905659651
pParse->aAlias[iAlias-1] = iReg;
5905759652
}
5905859653
}
5905959654
return iReg;
59655
+#else
59656
+ UNUSED_PARAMETER(iAlias);
59657
+ return sqlite3ExprCodeTarget(pParse, pExpr, target);
59658
+#endif
5906059659
}
5906159660
5906259661
/*
5906359662
** Generate code into the current Vdbe to evaluate the given
5906459663
** expression. Attempt to store the results in register "target".
@@ -59124,12 +59723,11 @@
5912459723
case TK_FLOAT: {
5912559724
codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
5912659725
break;
5912759726
}
5912859727
case TK_STRING: {
59129
- sqlite3DequoteExpr(pExpr);
59130
- sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
59728
+ sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0,
5913159729
(char*)pExpr->token.z, pExpr->token.n);
5913259730
break;
5913359731
}
5913459732
case TK_NULL: {
5913559733
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
@@ -59434,13 +60032,12 @@
5943460032
5943560033
5943660034
/* Code the <expr> from "<expr> IN (...)". The temporary table
5943760035
** pExpr->iTable contains the values that make up the (...) set.
5943860036
*/
59439
- pParse->disableColCache++;
60037
+ sqlite3ExprCachePush(pParse);
5944060038
sqlite3ExprCode(pParse, pExpr->pLeft, target);
59441
- pParse->disableColCache--;
5944260039
j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target);
5944360040
if( eType==IN_INDEX_ROWID ){
5944460041
j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target);
5944560042
j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target);
5944660043
sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
@@ -59497,10 +60094,11 @@
5949760094
sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target);
5949860095
}
5949960096
}
5950060097
sqlite3VdbeJumpHere(v, j2);
5950160098
sqlite3VdbeJumpHere(v, j5);
60099
+ sqlite3ExprCachePop(pParse, 1);
5950260100
VdbeComment((v, "end IN expr r%d", target));
5950360101
break;
5950460102
}
5950560103
#endif
5950660104
/*
@@ -59573,10 +60171,11 @@
5957360171
struct ExprList_item *aListelem; /* Array of WHEN terms */
5957460172
Expr opCompare; /* The X==Ei expression */
5957560173
Expr cacheX; /* Cached expression X */
5957660174
Expr *pX; /* The X expression */
5957760175
Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
60176
+ VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
5957860177
5957960178
assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
5958060179
assert((pExpr->x.pList->nExpr % 2) == 0);
5958160180
assert(pExpr->x.pList->nExpr > 0);
5958260181
pEList = pExpr->x.pList;
@@ -59591,12 +60190,12 @@
5959160190
cacheX.op = TK_REGISTER;
5959260191
opCompare.op = TK_EQ;
5959360192
opCompare.pLeft = &cacheX;
5959460193
pTest = &opCompare;
5959560194
}
59596
- pParse->disableColCache++;
5959760195
for(i=0; i<nExpr; i=i+2){
60196
+ sqlite3ExprCachePush(pParse);
5959860197
if( pX ){
5959960198
assert( pTest!=0 );
5960060199
opCompare.pRight = aListelem[i].pExpr;
5960160200
}else{
5960260201
pTest = aListelem[i].pExpr;
@@ -59606,20 +60205,23 @@
5960660205
sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
5960760206
testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
5960860207
testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
5960960208
sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
5961060209
sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
60210
+ sqlite3ExprCachePop(pParse, 1);
5961160211
sqlite3VdbeResolveLabel(v, nextCase);
5961260212
}
5961360213
if( pExpr->pRight ){
60214
+ sqlite3ExprCachePush(pParse);
5961460215
sqlite3ExprCode(pParse, pExpr->pRight, target);
60216
+ sqlite3ExprCachePop(pParse, 1);
5961560217
}else{
5961660218
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
5961760219
}
60220
+ assert( db->mallocFailed || pParse->nErr>0
60221
+ || pParse->iCacheLevel==iCacheLevel );
5961860222
sqlite3VdbeResolveLabel(v, endLabel);
59619
- assert( pParse->disableColCache>0 );
59620
- pParse->disableColCache--;
5962160223
break;
5962260224
}
5962360225
#ifndef SQLITE_OMIT_TRIGGER
5962460226
case TK_RAISE: {
5962560227
if( !pParse->trigStack ){
@@ -59629,11 +60231,10 @@
5962960231
}
5963060232
if( pExpr->affinity!=OE_Ignore ){
5963160233
assert( pExpr->affinity==OE_Rollback ||
5963260234
pExpr->affinity == OE_Abort ||
5963360235
pExpr->affinity == OE_Fail );
59634
- sqlite3DequoteExpr(pExpr);
5963560236
sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->affinity, 0,
5963660237
(char*)pExpr->token.z, pExpr->token.n);
5963760238
} else {
5963860239
assert( pExpr->affinity == OE_Ignore );
5963960240
sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
@@ -59890,27 +60491,21 @@
5989060491
op = pExpr->op;
5989160492
switch( op ){
5989260493
case TK_AND: {
5989360494
int d2 = sqlite3VdbeMakeLabel(v);
5989460495
testcase( jumpIfNull==0 );
59895
- testcase( pParse->disableColCache==0 );
60496
+ sqlite3ExprCachePush(pParse);
5989660497
sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
59897
- pParse->disableColCache++;
5989860498
sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
59899
- assert( pParse->disableColCache>0 );
59900
- pParse->disableColCache--;
5990160499
sqlite3VdbeResolveLabel(v, d2);
60500
+ sqlite3ExprCachePop(pParse, 1);
5990260501
break;
5990360502
}
5990460503
case TK_OR: {
5990560504
testcase( jumpIfNull==0 );
59906
- testcase( pParse->disableColCache==0 );
5990760505
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
59908
- pParse->disableColCache++;
5990960506
sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
59910
- assert( pParse->disableColCache>0 );
59911
- pParse->disableColCache--;
5991260507
break;
5991360508
}
5991460509
case TK_NOT: {
5991560510
testcase( jumpIfNull==0 );
5991660511
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
@@ -60050,28 +60645,22 @@
6005060645
assert( pExpr->op!=TK_GE || op==OP_Lt );
6005160646
6005260647
switch( pExpr->op ){
6005360648
case TK_AND: {
6005460649
testcase( jumpIfNull==0 );
60055
- testcase( pParse->disableColCache==0 );
6005660650
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
60057
- pParse->disableColCache++;
6005860651
sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
60059
- assert( pParse->disableColCache>0 );
60060
- pParse->disableColCache--;
6006160652
break;
6006260653
}
6006360654
case TK_OR: {
6006460655
int d2 = sqlite3VdbeMakeLabel(v);
6006560656
testcase( jumpIfNull==0 );
60066
- testcase( pParse->disableColCache==0 );
60657
+ sqlite3ExprCachePush(pParse);
6006760658
sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
60068
- pParse->disableColCache++;
6006960659
sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
60070
- assert( pParse->disableColCache>0 );
60071
- pParse->disableColCache--;
6007260660
sqlite3VdbeResolveLabel(v, d2);
60661
+ sqlite3ExprCachePop(pParse, 1);
6007360662
break;
6007460663
}
6007560664
case TK_NOT: {
6007660665
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
6007760666
break;
@@ -60403,21 +60992,37 @@
6040360992
}
6040460993
}
6040560994
}
6040660995
6040760996
/*
60408
-** Allocate or deallocate temporary use registers during code generation.
60997
+** Allocate a single new register for use to hold some intermediate result.
6040960998
*/
6041060999
SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
6041161000
if( pParse->nTempReg==0 ){
6041261001
return ++pParse->nMem;
6041361002
}
6041461003
return pParse->aTempReg[--pParse->nTempReg];
6041561004
}
61005
+
61006
+/*
61007
+** Deallocate a register, making available for reuse for some other
61008
+** purpose.
61009
+**
61010
+** If a register is currently being used by the column cache, then
61011
+** the dallocation is deferred until the column cache line that uses
61012
+** the register becomes stale.
61013
+*/
6041661014
SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
6041761015
if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
60418
- sqlite3ExprWritableRegister(pParse, iReg);
61016
+ int i;
61017
+ struct yColCache *p;
61018
+ for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
61019
+ if( p->iReg==iReg ){
61020
+ p->tempReg = 1;
61021
+ return;
61022
+ }
61023
+ }
6041961024
pParse->aTempReg[pParse->nTempReg++] = iReg;
6042061025
}
6042161026
}
6042261027
6042361028
/*
@@ -60457,11 +61062,11 @@
6045761062
**
6045861063
*************************************************************************
6045961064
** This file contains C code routines that used to generate VDBE code
6046061065
** that implements the ALTER TABLE command.
6046161066
**
60462
-** $Id: alter.c,v 1.55 2009/03/24 15:08:10 drh Exp $
61067
+** $Id: alter.c,v 1.57 2009/04/16 16:30:18 drh Exp $
6046361068
*/
6046461069
6046561070
/*
6046661071
** The code in this file only exists if we are not omitting the
6046761072
** ALTER TABLE logic from the build.
@@ -60669,11 +61274,11 @@
6066961274
#ifndef SQLITE_OMIT_TRIGGER
6067061275
Trigger *pTrig;
6067161276
#endif
6067261277
6067361278
v = sqlite3GetVdbe(pParse);
60674
- if( !v ) return;
61279
+ if( NEVER(v==0) ) return;
6067561280
assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
6067661281
iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
6067761282
assert( iDb>=0 );
6067861283
6067961284
#ifndef SQLITE_OMIT_TRIGGER
@@ -60723,11 +61328,11 @@
6072361328
#ifndef SQLITE_OMIT_TRIGGER
6072461329
char *zWhere = 0; /* Where clause to locate temp triggers */
6072561330
#endif
6072661331
int isVirtualRename = 0; /* True if this is a v-table with an xRename() */
6072761332
60728
- if( db->mallocFailed ) goto exit_rename_table;
61333
+ if( NEVER(db->mallocFailed) ) goto exit_rename_table;
6072961334
assert( pSrc->nSrc==1 );
6073061335
assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
6073161336
6073261337
pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
6073361338
if( !pTab ) goto exit_rename_table;
@@ -60956,11 +61561,11 @@
6095661561
6095761562
/* Modify the CREATE TABLE statement. */
6095861563
zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
6095961564
if( zCol ){
6096061565
char *zEnd = &zCol[pColDef->n-1];
60961
- while( (zEnd>zCol && *zEnd==';') || sqlite3Isspace(*zEnd) ){
61566
+ while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
6096261567
*zEnd-- = '\0';
6096361568
}
6096461569
sqlite3NestedParse(pParse,
6096561570
"UPDATE \"%w\".%s SET "
6096661571
"sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
@@ -61087,11 +61692,11 @@
6108761692
** May you share freely, never taking more than you give.
6108861693
**
6108961694
*************************************************************************
6109061695
** This file contains code associated with the ANALYZE command.
6109161696
**
61092
-** @(#) $Id: analyze.c,v 1.51 2009/02/28 10:47:42 danielk1977 Exp $
61697
+** @(#) $Id: analyze.c,v 1.52 2009/04/16 17:45:48 drh Exp $
6109361698
*/
6109461699
#ifndef SQLITE_OMIT_ANALYZE
6109561700
6109661701
/*
6109761702
** This routine generates code that opens the sqlite_stat1 table on cursor
@@ -61175,11 +61780,11 @@
6117561780
int endOfLoop; /* The end of the loop */
6117661781
int addr; /* The address of an instruction */
6117761782
int iDb; /* Index of database containing pTab */
6117861783
6117961784
v = sqlite3GetVdbe(pParse);
61180
- if( v==0 || pTab==0 || pTab->pIndex==0 ){
61785
+ if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
6118161786
/* Do no analysis for tables that have no indices */
6118261787
return;
6118361788
}
6118461789
assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
6118561790
iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
@@ -61375,17 +61980,18 @@
6137561980
assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
6137661981
if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
6137761982
return;
6137861983
}
6137961984
61985
+ assert( pName2!=0 || pName1==0 );
6138061986
if( pName1==0 ){
6138161987
/* Form 1: Analyze everything */
6138261988
for(i=0; i<db->nDb; i++){
6138361989
if( i==1 ) continue; /* Do not analyze the TEMP database */
6138461990
analyzeDatabase(pParse, i);
6138561991
}
61386
- }else if( pName2==0 || pName2->n==0 ){
61992
+ }else if( pName2->n==0 ){
6138761993
/* Form 2: Analyze the database or table named */
6138861994
iDb = sqlite3FindDb(db, pName1);
6138961995
if( iDb>=0 ){
6139061996
analyzeDatabase(pParse, iDb);
6139161997
}else{
@@ -61520,11 +62126,11 @@
6152062126
** May you share freely, never taking more than you give.
6152162127
**
6152262128
*************************************************************************
6152362129
** This file contains code used to implement the ATTACH and DETACH commands.
6152462130
**
61525
-** $Id: attach.c,v 1.84 2009/04/08 13:51:51 drh Exp $
62131
+** $Id: attach.c,v 1.90 2009/05/01 06:19:21 danielk1977 Exp $
6152662132
*/
6152762133
6152862134
#ifndef SQLITE_OMIT_ATTACH
6152962135
/*
6153062136
** Resolve an expression that was part of an ATTACH or DETACH statement. This
@@ -61582,11 +62188,10 @@
6158262188
sqlite3 *db = sqlite3_context_db_handle(context);
6158362189
const char *zName;
6158462190
const char *zFile;
6158562191
Db *aNew;
6158662192
char *zErrDyn = 0;
61587
- char zErr[128];
6158862193
6158962194
UNUSED_PARAMETER(NotUsed);
6159062195
6159162196
zFile = (const char *)sqlite3_value_text(argv[0]);
6159262197
zName = (const char *)sqlite3_value_text(argv[1]);
@@ -61598,26 +62203,24 @@
6159862203
** * Too many attached databases,
6159962204
** * Transaction currently open
6160062205
** * Specified database name already being used.
6160162206
*/
6160262207
if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
61603
- sqlite3_snprintf(
61604
- sizeof(zErr), zErr, "too many attached databases - max %d",
62208
+ zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
6160562209
db->aLimit[SQLITE_LIMIT_ATTACHED]
6160662210
);
6160762211
goto attach_error;
6160862212
}
6160962213
if( !db->autoCommit ){
61610
- sqlite3_snprintf(sizeof(zErr), zErr,
61611
- "cannot ATTACH database within transaction");
62214
+ zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
6161262215
goto attach_error;
6161362216
}
6161462217
for(i=0; i<db->nDb; i++){
6161562218
char *z = db->aDb[i].zName;
61616
- if( z && zName && sqlite3StrICmp(z, zName)==0 ){
61617
- sqlite3_snprintf(sizeof(zErr), zErr,
61618
- "database %s is already in use", zName);
62219
+ assert( z && zName );
62220
+ if( sqlite3StrICmp(z, zName)==0 ){
62221
+ zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
6161962222
goto attach_error;
6162062223
}
6162162224
}
6162262225
6162362226
/* Allocate the new entry in the db->aDb[] array and initialise the schema
@@ -61630,29 +62233,33 @@
6163062233
}else{
6163162234
aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
6163262235
if( aNew==0 ) return;
6163362236
}
6163462237
db->aDb = aNew;
61635
- aNew = &db->aDb[db->nDb++];
62238
+ aNew = &db->aDb[db->nDb];
6163662239
memset(aNew, 0, sizeof(*aNew));
6163762240
6163862241
/* Open the database file. If the btree is successfully opened, use
6163962242
** it to obtain the database schema. At this point the schema may
6164062243
** or may not be initialised.
6164162244
*/
6164262245
rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
6164362246
db->openFlags | SQLITE_OPEN_MAIN_DB,
6164462247
&aNew->pBt);
61645
- if( rc==SQLITE_OK ){
62248
+ db->nDb++;
62249
+ if( rc==SQLITE_CONSTRAINT ){
62250
+ rc = SQLITE_ERROR;
62251
+ zErrDyn = sqlite3MPrintf(db, "database is already attached");
62252
+ }else if( rc==SQLITE_OK ){
6164662253
Pager *pPager;
6164762254
aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
6164862255
if( !aNew->pSchema ){
6164962256
rc = SQLITE_NOMEM;
6165062257
}else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
61651
- sqlite3_snprintf(sizeof(zErr), zErr,
62258
+ zErrDyn = sqlite3MPrintf(db,
6165262259
"attached databases must use the same text encoding as main database");
61653
- goto attach_error;
62260
+ rc = SQLITE_ERROR;
6165462261
}
6165562262
pPager = sqlite3BtreePager(aNew->pBt);
6165662263
sqlite3PagerLockingMode(pPager, db->dfltLockMode);
6165762264
sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
6165862265
}
@@ -61711,13 +62318,14 @@
6171162318
}
6171262319
sqlite3ResetInternalSchema(db, 0);
6171362320
db->nDb = iDb;
6171462321
if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
6171562322
db->mallocFailed = 1;
61716
- sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
61717
- }else{
61718
- sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
62323
+ sqlite3DbFree(db, zErrDyn);
62324
+ zErrDyn = sqlite3MPrintf(db, "out of memory");
62325
+ }else if( zErrDyn==0 ){
62326
+ zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
6171962327
}
6172062328
goto attach_error;
6172162329
}
6172262330
6172362331
return;
@@ -61725,13 +62333,10 @@
6172562333
attach_error:
6172662334
/* Return an error if we get here */
6172762335
if( zErrDyn ){
6172862336
sqlite3_result_error(context, zErrDyn, -1);
6172962337
sqlite3DbFree(db, zErrDyn);
61730
- }else{
61731
- zErr[sizeof(zErr)-1] = 0;
61732
- sqlite3_result_error(context, zErr, -1);
6173362338
}
6173462339
if( rc ) sqlite3_result_error_code(context, rc);
6173562340
}
6173662341
6173762342
/*
@@ -61919,11 +62524,11 @@
6191962524
const char *zType, /* "view", "trigger", or "index" */
6192062525
const Token *pName /* Name of the view, trigger, or index */
6192162526
){
6192262527
sqlite3 *db;
6192362528
61924
- if( iDb<0 || iDb==1 ) return 0;
62529
+ if( NEVER(iDb<0) || iDb==1 ) return 0;
6192562530
db = pParse->db;
6192662531
assert( db->nDb>iDb );
6192762532
pFix->pParse = pParse;
6192862533
pFix->zDb = db->aDb[iDb].zName;
6192962534
pFix->zType = zType;
@@ -61951,11 +62556,11 @@
6195162556
){
6195262557
int i;
6195362558
const char *zDb;
6195462559
struct SrcList_item *pItem;
6195562560
61956
- if( pList==0 ) return 0;
62561
+ if( NEVER(pList==0) ) return 0;
6195762562
zDb = pFix->zDb;
6195862563
for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
6195962564
if( pItem->zDatabase==0 ){
6196062565
pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
6196162566
}else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
@@ -62064,11 +62669,11 @@
6206462669
** This file contains code used to implement the sqlite3_set_authorizer()
6206562670
** API. This facility is an optional feature of the library. Embedded
6206662671
** systems that do not need this facility may omit it by recompiling
6206762672
** the library with -DSQLITE_OMIT_AUTHORIZATION=1
6206862673
**
62069
-** $Id: auth.c,v 1.29 2007/09/18 15:55:07 drh Exp $
62674
+** $Id: auth.c,v 1.31 2009/05/04 18:01:40 drh Exp $
6207062675
*/
6207162676
6207262677
/*
6207362678
** All of the code in this file may be omitted by defining a single
6207462679
** macro.
@@ -62135,14 +62740,12 @@
6213562740
6213662741
/*
6213762742
** Write an error message into pParse->zErrMsg that explains that the
6213862743
** user-supplied authorization function returned an illegal value.
6213962744
*/
62140
-static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
62141
- sqlite3ErrorMsg(pParse, "illegal return value (%d) from the "
62142
- "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
62143
- "or SQLITE_DENY", rc);
62745
+static void sqliteAuthBadReturnCode(Parse *pParse){
62746
+ sqlite3ErrorMsg(pParse, "authorizer malfunction");
6214462747
pParse->rc = SQLITE_ERROR;
6214562748
}
6214662749
6214762750
/*
6214862751
** The pExpr should be a TK_COLUMN expression. The table referred to
@@ -62167,30 +62770,34 @@
6216762770
const char *zDBase; /* Name of database being accessed */
6216862771
TriggerStack *pStack; /* The stack of current triggers */
6216962772
int iDb; /* The index of the database the expression refers to */
6217062773
6217162774
if( db->xAuth==0 ) return;
62172
- if( pExpr->op!=TK_COLUMN ) return;
62775
+ assert( pExpr->op==TK_COLUMN );
6217362776
iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
6217462777
if( iDb<0 ){
6217562778
/* An attempt to read a column out of a subquery or other
6217662779
** temporary table. */
6217762780
return;
6217862781
}
62179
- for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
62180
- if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
62181
- }
62182
- if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
62782
+ if( pTabList ){
62783
+ for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
62784
+ if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
62785
+ }
62786
+ assert( iSrc<pTabList->nSrc );
6218362787
pTab = pTabList->a[iSrc].pTab;
62184
- }else if( (pStack = pParse->trigStack)!=0 ){
62185
- /* This must be an attempt to read the NEW or OLD pseudo-tables
62186
- ** of a trigger.
62187
- */
62188
- assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
62189
- pTab = pStack->pTab;
62190
- }
62191
- if( pTab==0 ) return;
62788
+ }else{
62789
+ pStack = pParse->trigStack;
62790
+ if( ALWAYS(pStack) ){
62791
+ /* This must be an attempt to read the NEW or OLD pseudo-tables
62792
+ ** of a trigger.
62793
+ */
62794
+ assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
62795
+ pTab = pStack->pTab;
62796
+ }
62797
+ }
62798
+ if( NEVER(pTab==0) ) return;
6219262799
if( pExpr->iColumn>=0 ){
6219362800
assert( pExpr->iColumn<pTab->nCol );
6219462801
zCol = pTab->aCol[pExpr->iColumn].zName;
6219562802
}else if( pTab->iPKey>=0 ){
6219662803
assert( pTab->iPKey<pTab->nCol );
@@ -62211,11 +62818,11 @@
6221162818
}else{
6221262819
sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
6221362820
}
6221462821
pParse->rc = SQLITE_AUTH;
6221562822
}else if( rc!=SQLITE_OK ){
62216
- sqliteAuthBadReturnCode(pParse, rc);
62823
+ sqliteAuthBadReturnCode(pParse);
6221762824
}
6221862825
}
6221962826
6222062827
/*
6222162828
** Do an authorization check using the code and arguments given. Return
@@ -62247,11 +62854,11 @@
6224762854
if( rc==SQLITE_DENY ){
6224862855
sqlite3ErrorMsg(pParse, "not authorized");
6224962856
pParse->rc = SQLITE_AUTH;
6225062857
}else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
6225162858
rc = SQLITE_DENY;
62252
- sqliteAuthBadReturnCode(pParse, rc);
62859
+ sqliteAuthBadReturnCode(pParse);
6225362860
}
6225462861
return rc;
6225562862
}
6225662863
6225762864
/*
@@ -62262,15 +62869,14 @@
6226262869
SQLITE_PRIVATE void sqlite3AuthContextPush(
6226362870
Parse *pParse,
6226462871
AuthContext *pContext,
6226562872
const char *zContext
6226662873
){
62874
+ assert( pParse );
6226762875
pContext->pParse = pParse;
62268
- if( pParse ){
62269
- pContext->zAuthContext = pParse->zAuthContext;
62270
- pParse->zAuthContext = zContext;
62271
- }
62876
+ pContext->zAuthContext = pParse->zAuthContext;
62877
+ pParse->zAuthContext = zContext;
6227262878
}
6227362879
6227462880
/*
6227562881
** Pop an authorization context that was previously pushed
6227662882
** by sqlite3AuthContextPush
@@ -62308,11 +62914,11 @@
6230862914
** creating ID lists
6230962915
** BEGIN TRANSACTION
6231062916
** COMMIT
6231162917
** ROLLBACK
6231262918
**
62313
-** $Id: build.c,v 1.528 2009/04/08 13:51:51 drh Exp $
62919
+** $Id: build.c,v 1.537 2009/05/06 18:42:21 drh Exp $
6231462920
*/
6231562921
6231662922
/*
6231762923
** This routine is called when a new SQL statement is beginning to
6231862924
** be parsed. Initialize the pParse structure as needed.
@@ -62443,11 +63049,13 @@
6244363049
sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
6244463050
for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
6244563051
if( (mask & pParse->cookieMask)==0 ) continue;
6244663052
sqlite3VdbeUsesBtree(v, iDb);
6244763053
sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
62448
- sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
63054
+ if( db->init.busy==0 ){
63055
+ sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
63056
+ }
6244963057
}
6245063058
#ifndef SQLITE_OMIT_VIRTUALTABLE
6245163059
{
6245263060
int i;
6245363061
for(i=0; i<pParse->nVtabLock; i++){
@@ -62473,11 +63081,11 @@
6247363081
if( v && pParse->nErr==0 && !db->mallocFailed ){
6247463082
#ifdef SQLITE_DEBUG
6247563083
FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
6247663084
sqlite3VdbeTrace(v, trace);
6247763085
#endif
62478
- assert( pParse->disableColCache==0 ); /* Disables and re-enables match */
63086
+ assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
6247963087
sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
6248063088
pParse->nTab, pParse->explain);
6248163089
pParse->rc = SQLITE_DONE;
6248263090
pParse->colNamesSet = 0;
6248363091
}else if( pParse->rc==SQLITE_OK ){
@@ -62544,11 +63152,11 @@
6254463152
SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
6254563153
Table *p = 0;
6254663154
int i;
6254763155
int nName;
6254863156
assert( zName!=0 );
62549
- nName = sqlite3Strlen(db, zName) + 1;
63157
+ nName = sqlite3Strlen30(zName);
6255063158
for(i=OMIT_TEMPDB; i<db->nDb; i++){
6255163159
int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
6255263160
if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
6255363161
p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
6255463162
if( p ) break;
@@ -62606,11 +63214,11 @@
6260663214
** using the ATTACH command.
6260763215
*/
6260863216
SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
6260963217
Index *p = 0;
6261063218
int i;
62611
- int nName = sqlite3Strlen(db, zName)+1;
63219
+ int nName = sqlite3Strlen30(zName);
6261263220
for(i=OMIT_TEMPDB; i<db->nDb; i++){
6261363221
int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
6261463222
Schema *pSchema = db->aDb[j].pSchema;
6261563223
if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
6261663224
assert( pSchema || (j==1 && !db->aDb[1].pBt) );
@@ -62642,11 +63250,11 @@
6264263250
static void sqlite3DeleteIndex(Index *p){
6264363251
Index *pOld;
6264463252
const char *zName = p->zName;
6264563253
6264663254
pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
62647
- sqlite3Strlen30(zName)+1, 0);
63255
+ sqlite3Strlen30(zName), 0);
6264863256
assert( pOld==0 || pOld==p );
6264963257
freeIndex(p);
6265063258
}
6265163259
6265263260
/*
@@ -62658,12 +63266,12 @@
6265863266
SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
6265963267
Index *pIndex;
6266063268
int len;
6266163269
Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
6266263270
62663
- len = sqlite3Strlen(db, zIdxName);
62664
- pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
63271
+ len = sqlite3Strlen30(zIdxName);
63272
+ pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
6266563273
if( pIndex ){
6266663274
if( pIndex->pTable->pIndex==pIndex ){
6266763275
pIndex->pTable->pIndex = pIndex->pNext;
6266863276
}else{
6266963277
Index *p;
@@ -62772,12 +63380,11 @@
6277263380
/*
6277363381
** Remove the memory data structures associated with the given
6277463382
** Table. No changes are made to disk by this routine.
6277563383
**
6277663384
** This routine just deletes the data structure. It does not unlink
62777
-** the table data structure from the hash table. Nor does it remove
62778
-** foreign keys from the sqlite.aFKey hash table. But it does destroy
63385
+** the table data structure from the hash table. But it does destroy
6277963386
** memory structures of the indices and foreign keys associated with
6278063387
** the table.
6278163388
*/
6278263389
SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
6278363390
Index *pIndex, *pNext;
@@ -62801,17 +63408,13 @@
6280163408
assert( pIndex->pSchema==pTable->pSchema );
6280263409
sqlite3DeleteIndex(pIndex);
6280363410
}
6280463411
6280563412
#ifndef SQLITE_OMIT_FOREIGN_KEY
62806
- /* Delete all foreign keys associated with this table. The keys
62807
- ** should have already been unlinked from the pSchema->aFKey hash table
62808
- */
63413
+ /* Delete all foreign keys associated with this table. */
6280963414
for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
6281063415
pNextFKey = pFKey->pNextFrom;
62811
- assert( sqlite3HashFind(&pTable->pSchema->aFKey,
62812
- pFKey->zTo, sqlite3Strlen30(pFKey->zTo)+1)!=pFKey );
6281363416
sqlite3DbFree(db, pFKey);
6281463417
}
6281563418
#endif
6281663419
6281763420
/* Delete the Table structure itself.
@@ -62831,54 +63434,40 @@
6283163434
** Unlink the given table from the hash tables and the delete the
6283263435
** table structure with all its indices and foreign keys.
6283363436
*/
6283463437
SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
6283563438
Table *p;
62836
- FKey *pF1, *pF2;
6283763439
Db *pDb;
6283863440
6283963441
assert( db!=0 );
6284063442
assert( iDb>=0 && iDb<db->nDb );
6284163443
assert( zTabName && zTabName[0] );
6284263444
pDb = &db->aDb[iDb];
6284363445
p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
62844
- sqlite3Strlen30(zTabName)+1,0);
62845
- if( p ){
62846
-#ifndef SQLITE_OMIT_FOREIGN_KEY
62847
- for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
62848
- int nTo = sqlite3Strlen30(pF1->zTo) + 1;
62849
- pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
62850
- if( pF2==pF1 ){
62851
- sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
62852
- }else{
62853
- while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
62854
- if( pF2 ){
62855
- pF2->pNextTo = pF1->pNextTo;
62856
- }
62857
- }
62858
- }
62859
-#endif
62860
- sqlite3DeleteTable(p);
62861
- }
63446
+ sqlite3Strlen30(zTabName),0);
63447
+ sqlite3DeleteTable(p);
6286263448
db->flags |= SQLITE_InternChanges;
6286363449
}
6286463450
6286563451
/*
6286663452
** Given a token, return a string that consists of the text of that
62867
-** token with any quotations removed. Space to hold the returned string
63453
+** token. Space to hold the returned string
6286863454
** is obtained from sqliteMalloc() and must be freed by the calling
6286963455
** function.
63456
+**
63457
+** Any quotation marks (ex: "name", 'name', [name], or `name`) that
63458
+** surround the body of the token are removed.
6287063459
**
6287163460
** Tokens are often just pointers into the original SQL text and so
6287263461
** are not \000 terminated and are not persistent. The returned string
6287363462
** is \000 terminated and is persistent.
6287463463
*/
6287563464
SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
6287663465
char *zName;
6287763466
if( pName ){
6287863467
zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
62879
- sqlite3Dequote(zName);
63468
+ if( pName->quoted ) sqlite3Dequote(zName);
6288063469
}else{
6288163470
zName = 0;
6288263471
}
6288363472
return zName;
6288463473
}
@@ -63563,11 +64152,11 @@
6356364152
pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
6356464153
if( !initbusy && (!pColl || !pColl->xCmp) ){
6356564154
pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
6356664155
if( !pColl ){
6356764156
if( nName<0 ){
63568
- nName = sqlite3Strlen(db, zName);
64157
+ nName = sqlite3Strlen30(zName);
6356964158
}
6357064159
sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
6357164160
pColl = 0;
6357264161
}
6357364162
}
@@ -63968,30 +64557,18 @@
6396864557
6396964558
/* Add the table to the in-memory representation of the database.
6397064559
*/
6397164560
if( db->init.busy && pParse->nErr==0 ){
6397264561
Table *pOld;
63973
- FKey *pFKey;
6397464562
Schema *pSchema = p->pSchema;
6397564563
pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
63976
- sqlite3Strlen30(p->zName)+1,p);
64564
+ sqlite3Strlen30(p->zName),p);
6397764565
if( pOld ){
6397864566
assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
6397964567
db->mallocFailed = 1;
6398064568
return;
6398164569
}
63982
-#ifndef SQLITE_OMIT_FOREIGN_KEY
63983
- for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
63984
- void *data;
63985
- int nTo = sqlite3Strlen30(pFKey->zTo) + 1;
63986
- pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
63987
- data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
63988
- if( data==(void *)pFKey ){
63989
- db->mallocFailed = 1;
63990
- }
63991
- }
63992
-#endif
6399364570
pParse->pNewTable = 0;
6399464571
db->nTable++;
6399564572
db->flags |= SQLITE_InternChanges;
6399664573
6399764574
#ifndef SQLITE_OMIT_ALTERTABLE
@@ -64494,13 +65071,11 @@
6449465071
** pTo table that the foreign key points to. flags contains all
6449565072
** information about the conflict resolution algorithms specified
6449665073
** in the ON DELETE, ON UPDATE and ON INSERT clauses.
6449765074
**
6449865075
** An FKey structure is created and added to the table currently
64499
-** under construction in the pParse->pNewTable field. The new FKey
64500
-** is not linked into db->aFKey at this point - that does not happen
64501
-** until sqlite3EndTable().
65076
+** under construction in the pParse->pNewTable field.
6450265077
**
6450365078
** The foreign key is set for IMMEDIATE processing. A subsequent call
6450465079
** to sqlite3DeferForeignKey() might change this to DEFERRED.
6450565080
*/
6450665081
SQLITE_PRIVATE void sqlite3CreateForeignKey(
@@ -64537,11 +65112,11 @@
6453765112
"columns in the referenced table");
6453865113
goto fk_end;
6453965114
}else{
6454065115
nCol = pFromCol->nExpr;
6454165116
}
64542
- nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
65117
+ nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
6454365118
if( pToCol ){
6454465119
for(i=0; i<pToCol->nExpr; i++){
6454565120
nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
6454665121
}
6454765122
}
@@ -64549,18 +65124,16 @@
6454965124
if( pFKey==0 ){
6455065125
goto fk_end;
6455165126
}
6455265127
pFKey->pFrom = p;
6455365128
pFKey->pNextFrom = p->pFKey;
64554
- z = (char*)&pFKey[1];
64555
- pFKey->aCol = (struct sColMap*)z;
64556
- z += sizeof(struct sColMap)*nCol;
65129
+ z = (char*)&pFKey->aCol[nCol];
6455765130
pFKey->zTo = z;
6455865131
memcpy(z, pTo->z, pTo->n);
6455965132
z[pTo->n] = 0;
65133
+ sqlite3Dequote(z);
6456065134
z += pTo->n+1;
64561
- pFKey->pNextTo = 0;
6456265135
pFKey->nCol = nCol;
6456365136
if( pFromCol==0 ){
6456465137
pFKey->aCol[0].iFrom = p->nCol-1;
6456565138
}else{
6456665139
for(i=0; i<nCol; i++){
@@ -64673,23 +65246,29 @@
6467365246
sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
6467465247
addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
6467565248
regRecord = sqlite3GetTempReg(pParse);
6467665249
regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
6467765250
if( pIndex->onError!=OE_None ){
64678
- int j1, j2;
64679
- int regRowid;
65251
+ const int regRowid = regIdxKey + pIndex->nColumn;
65252
+ const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
65253
+ void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
6468065254
64681
- regRowid = regIdxKey + pIndex->nColumn;
64682
- j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn);
64683
- j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx,
64684
- 0, regRowid, SQLITE_INT_TO_PTR(regRecord), P4_INT32);
65255
+ /* The registers accessed by the OP_IsUnique opcode were allocated
65256
+ ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
65257
+ ** call above. Just before that function was freed they were released
65258
+ ** (made available to the compiler for reuse) using
65259
+ ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
65260
+ ** opcode use the values stored within seems dangerous. However, since
65261
+ ** we can be sure that no other temp registers have been allocated
65262
+ ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
65263
+ */
65264
+ sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
6468565265
sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
6468665266
"indexed columns are not unique", P4_STATIC);
64687
- sqlite3VdbeJumpHere(v, j1);
64688
- sqlite3VdbeJumpHere(v, j2);
6468965267
}
6469065268
sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
65269
+ sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
6469165270
sqlite3ReleaseTempReg(pParse, regRecord);
6469265271
sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
6469365272
sqlite3VdbeJumpHere(v, addr1);
6469465273
sqlite3VdbeAddOp1(v, OP_Close, iTab);
6469565274
sqlite3VdbeAddOp1(v, OP_Close, iIdx);
@@ -64868,10 +65447,11 @@
6486865447
** So create a fake list to simulate this.
6486965448
*/
6487065449
if( pList==0 ){
6487165450
nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
6487265451
nullId.n = sqlite3Strlen30((char*)nullId.z);
65452
+ nullId.quoted = 0;
6487365453
pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
6487465454
if( pList==0 ) goto exit_create_index;
6487565455
pList->a[0].sortOrder = (u8)sortOrder;
6487665456
}
6487765457
@@ -65024,11 +65604,11 @@
6502465604
** in-memory database structures.
6502565605
*/
6502665606
if( db->init.busy ){
6502765607
Index *p;
6502865608
p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
65029
- pIndex->zName, sqlite3Strlen30(pIndex->zName)+1,
65609
+ pIndex->zName, sqlite3Strlen30(pIndex->zName),
6503065610
pIndex);
6503165611
if( p ){
6503265612
assert( p==pIndex ); /* Malloc must have failed */
6503365613
db->mallocFailed = 1;
6503465614
goto exit_create_index;
@@ -65981,11 +66561,11 @@
6598166561
*************************************************************************
6598266562
**
6598366563
** This file contains functions used to access the internal hash tables
6598466564
** of user defined functions and collation sequences.
6598566565
**
65986
-** $Id: callback.c,v 1.37 2009/03/24 15:08:10 drh Exp $
66566
+** $Id: callback.c,v 1.39 2009/05/03 20:23:53 drh Exp $
6598766567
*/
6598866568
6598966569
6599066570
/*
6599166571
** Invoke the 'collation needed' callback to request a collation sequence
@@ -65992,11 +66572,11 @@
6599266572
** in the database text encoding of name zName, length nName.
6599366573
** If the collation sequence
6599466574
*/
6599566575
static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
6599666576
assert( !db->xCollNeeded || !db->xCollNeeded16 );
65997
- if( nName<0 ) nName = sqlite3Strlen(db, zName);
66577
+ if( nName<0 ) nName = sqlite3Strlen30(zName);
6599866578
if( db->xCollNeeded ){
6599966579
char *zExternal = sqlite3DbStrNDup(db, zName, nName);
6600066580
if( !zExternal ) return;
6600166581
db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
6600266582
sqlite3DbFree(db, zExternal);
@@ -66125,11 +66705,11 @@
6612566705
const char *zName,
6612666706
int nName,
6612766707
int create
6612866708
){
6612966709
CollSeq *pColl;
66130
- if( nName<0 ) nName = sqlite3Strlen(db, zName);
66710
+ if( nName<0 ) nName = sqlite3Strlen30(zName);
6613166711
pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
6613266712
6613366713
if( 0==pColl && create ){
6613466714
pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
6613566715
if( pColl ){
@@ -66380,18 +66960,17 @@
6638066960
HashElem *pElem;
6638166961
Schema *pSchema = (Schema *)p;
6638266962
6638366963
temp1 = pSchema->tblHash;
6638466964
temp2 = pSchema->trigHash;
66385
- sqlite3HashInit(&pSchema->trigHash, 0);
66386
- sqlite3HashClear(&pSchema->aFKey);
66965
+ sqlite3HashInit(&pSchema->trigHash);
6638766966
sqlite3HashClear(&pSchema->idxHash);
6638866967
for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
6638966968
sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
6639066969
}
6639166970
sqlite3HashClear(&temp2);
66392
- sqlite3HashInit(&pSchema->tblHash, 0);
66971
+ sqlite3HashInit(&pSchema->tblHash);
6639366972
for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
6639466973
Table *pTab = sqliteHashData(pElem);
6639566974
assert( pTab->dbMem==0 );
6639666975
sqlite3DeleteTable(pTab);
6639766976
}
@@ -66412,14 +66991,13 @@
6641266991
p = (Schema *)sqlite3MallocZero(sizeof(Schema));
6641366992
}
6641466993
if( !p ){
6641566994
db->mallocFailed = 1;
6641666995
}else if ( 0==p->file_format ){
66417
- sqlite3HashInit(&p->tblHash, 0);
66418
- sqlite3HashInit(&p->idxHash, 0);
66419
- sqlite3HashInit(&p->trigHash, 0);
66420
- sqlite3HashInit(&p->aFKey, 1);
66996
+ sqlite3HashInit(&p->tblHash);
66997
+ sqlite3HashInit(&p->idxHash);
66998
+ sqlite3HashInit(&p->trigHash);
6642166999
p->enc = SQLITE_UTF8;
6642267000
}
6642367001
return p;
6642467002
}
6642567003
@@ -66437,11 +67015,11 @@
6643767015
**
6643867016
*************************************************************************
6643967017
** This file contains C code routines that are called by the parser
6644067018
** in order to generate code for DELETE FROM statements.
6644167019
**
66442
-** $Id: delete.c,v 1.198 2009/03/05 03:48:07 shane Exp $
67020
+** $Id: delete.c,v 1.201 2009/05/01 21:13:37 drh Exp $
6644367021
*/
6644467022
6644567023
/*
6644667024
** Look up every table that is named in pSrc. If any table is not found,
6644767025
** add an error message to pParse->zErrMsg and return NULL. If all tables
@@ -66486,30 +67064,10 @@
6648667064
}
6648767065
#endif
6648867066
return 0;
6648967067
}
6649067068
66491
-/*
66492
-** Generate code that will open a table for reading.
66493
-*/
66494
-SQLITE_PRIVATE void sqlite3OpenTable(
66495
- Parse *p, /* Generate code into this VDBE */
66496
- int iCur, /* The cursor number of the table */
66497
- int iDb, /* The database index in sqlite3.aDb[] */
66498
- Table *pTab, /* The table to be opened */
66499
- int opcode /* OP_OpenRead or OP_OpenWrite */
66500
-){
66501
- Vdbe *v;
66502
- if( IsVirtual(pTab) ) return;
66503
- v = sqlite3GetVdbe(p);
66504
- assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
66505
- sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
66506
- sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
66507
- sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
66508
- VdbeComment((v, "%s", pTab->zName));
66509
-}
66510
-
6651167069
6651267070
#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
6651367071
/*
6651467072
** Evaluate a view and store its result in an ephemeral table. The
6651567073
** pWhere argument is an optional WHERE clause that restricts the
@@ -66531,10 +67089,11 @@
6653167089
Token viewName;
6653267090
6653367091
pWhere = sqlite3ExprDup(db, pWhere, 0);
6653467092
viewName.z = (u8*)pView->zName;
6653567093
viewName.n = (unsigned int)sqlite3Strlen30((const char*)viewName.z);
67094
+ viewName.quoted = 0;
6653667095
pFrom = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, &viewName, pDup, 0,0);
6653767096
pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
6653867097
}
6653967098
sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
6654067099
sqlite3Select(pParse, pDup, &dest);
@@ -66801,14 +67360,12 @@
6680167360
** It is easier just to erase the whole table. Note, however, that
6680267361
** this means that the row change count will be incorrect.
6680367362
*/
6680467363
if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) ){
6680567364
assert( !isView );
66806
- sqlite3VdbeAddOp3(v, OP_Clear, pTab->tnum, iDb, memCnt);
66807
- if( !pParse->nested ){
66808
- sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
66809
- }
67365
+ sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
67366
+ pTab->zName, P4_STATIC);
6681067367
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
6681167368
assert( pIdx->pSchema==pTab->pSchema );
6681267369
sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
6681367370
}
6681467371
}else
@@ -66817,17 +67374,19 @@
6681767374
** the table and pick which records to delete.
6681867375
*/
6681967376
{
6682067377
int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
6682167378
int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
67379
+ int regRowid; /* Actual register containing rowids */
6682267380
6682367381
/* Collect rowids of every row to be deleted.
6682467382
*/
6682567383
sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
66826
- pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
66827
- WHERE_FILL_ROWSET, iRowSet);
67384
+ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
6682867385
if( pWInfo==0 ) goto delete_from_cleanup;
67386
+ regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
67387
+ sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
6682967388
if( db->flags & SQLITE_CountRows ){
6683067389
sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
6683167390
}
6683267391
sqlite3WhereEnd(pWInfo);
6683367392
@@ -67074,11 +67633,11 @@
6707467633
**
6707567634
** There is only one exported symbol in this file - the function
6707667635
** sqliteRegisterBuildinFunctions() found at the bottom of the file.
6707767636
** All other code has file scope.
6707867637
**
67079
-** $Id: func.c,v 1.231 2009/04/08 23:04:14 drh Exp $
67638
+** $Id: func.c,v 1.234 2009/04/20 12:07:37 drh Exp $
6708067639
*/
6708167640
6708267641
/*
6708367642
** Return the collating function associated with a function.
6708467643
*/
@@ -68233,16 +68792,18 @@
6823368792
p = sqlite3_aggregate_context(context, sizeof(*p));
6823468793
if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
6823568794
p->n++;
6823668795
}
6823768796
68797
+#ifndef SQLITE_OMIT_DEPRECATED
6823868798
/* The sqlite3_aggregate_count() function is deprecated. But just to make
6823968799
** sure it still operates correctly, verify that its count agrees with our
6824068800
** internal count when using count(*) and when the total count can be
6824168801
** expressed as a 32-bit integer. */
6824268802
assert( argc==1 || p==0 || p->n>0x7fffffff
6824368803
|| p->n==sqlite3_aggregate_count(context) );
68804
+#endif
6824468805
}
6824568806
static void countFinalize(sqlite3_context *context){
6824668807
CountCtx *p;
6824768808
p = sqlite3_aggregate_context(context, 0);
6824868809
sqlite3_result_int64(context, p ? p->n : 0);
@@ -68312,13 +68873,19 @@
6831268873
if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
6831368874
pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
6831468875
6831568876
if( pAccum ){
6831668877
sqlite3 *db = sqlite3_context_db_handle(context);
68878
+ int n;
6831768879
pAccum->useMalloc = 1;
6831868880
pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
68319
- if( pAccum->nChar ){
68881
+#ifdef SQLITE_OMIT_DEPRECATED
68882
+ n = context->pMem->n;
68883
+#else
68884
+ n = sqlite3_aggregate_count(context);
68885
+#endif
68886
+ if( n>1 ){
6832068887
if( argc==2 ){
6832168888
zSep = (char*)sqlite3_value_text(argv[1]);
6832268889
nSep = sqlite3_value_bytes(argv[1]);
6832368890
}else{
6832468891
zSep = ",";
@@ -68539,12 +69106,32 @@
6853969106
**
6854069107
*************************************************************************
6854169108
** This file contains C code routines that are called by the parser
6854269109
** to handle INSERT statements in SQLite.
6854369110
**
68544
-** $Id: insert.c,v 1.260 2009/02/28 10:47:42 danielk1977 Exp $
69111
+** $Id: insert.c,v 1.267 2009/05/04 11:42:30 danielk1977 Exp $
6854569112
*/
69113
+
69114
+/*
69115
+** Generate code that will open a table for reading.
69116
+*/
69117
+SQLITE_PRIVATE void sqlite3OpenTable(
69118
+ Parse *p, /* Generate code into this VDBE */
69119
+ int iCur, /* The cursor number of the table */
69120
+ int iDb, /* The database index in sqlite3.aDb[] */
69121
+ Table *pTab, /* The table to be opened */
69122
+ int opcode /* OP_OpenRead or OP_OpenWrite */
69123
+){
69124
+ Vdbe *v;
69125
+ if( IsVirtual(pTab) ) return;
69126
+ v = sqlite3GetVdbe(p);
69127
+ assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
69128
+ sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
69129
+ sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
69130
+ sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
69131
+ VdbeComment((v, "%s", pTab->zName));
69132
+}
6854669133
6854769134
/*
6854869135
** Set P4 of the most recently inserted opcode to a column affinity
6854969136
** string for index pIdx. A column affinity string has one character
6855069137
** for each column in the table, according to the affinity of the column:
@@ -68941,11 +69528,11 @@
6894169528
6894269529
/* Locate the table into which we will be inserting new information.
6894369530
*/
6894469531
assert( pTabList->nSrc==1 );
6894569532
zTab = pTabList->a[0].zName;
68946
- if( zTab==0 ) goto insert_cleanup;
69533
+ if( NEVER(zTab==0) ) goto insert_cleanup;
6894769534
pTab = sqlite3SrcListLookup(pParse, pTabList);
6894869535
if( pTab==0 ){
6894969536
goto insert_cleanup;
6895069537
}
6895169538
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
@@ -69063,11 +69650,12 @@
6906369650
j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
6906469651
VdbeComment((v, "Jump over SELECT coroutine"));
6906569652
6906669653
/* Resolve the expressions in the SELECT statement and execute it. */
6906769654
rc = sqlite3Select(pParse, pSelect, &dest);
69068
- if( rc || pParse->nErr || db->mallocFailed ){
69655
+ assert( pParse->nErr==0 || rc );
69656
+ if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
6906969657
goto insert_cleanup;
6907069658
}
6907169659
sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
6907269660
sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */
6907369661
sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
@@ -69149,11 +69737,11 @@
6914969737
}
6915069738
}
6915169739
if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
6915269740
sqlite3ErrorMsg(pParse,
6915369741
"table %S has %d columns but %d values were supplied",
69154
- pTabList, 0, pTab->nCol, nColumn);
69742
+ pTabList, 0, pTab->nCol-nHidden, nColumn);
6915569743
goto insert_cleanup;
6915669744
}
6915769745
if( pColumn!=0 && nColumn!=pColumn->nId ){
6915869746
sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
6915969747
goto insert_cleanup;
@@ -69287,16 +69875,18 @@
6928769875
** not happened yet) so we substitute a rowid of -1
6928869876
*/
6928969877
regTrigRowid = sqlite3GetTempReg(pParse);
6929069878
if( keyColumn<0 ){
6929169879
sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
69292
- }else if( useTempTable ){
69293
- sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regTrigRowid);
6929469880
}else{
6929569881
int j1;
69296
- assert( pSelect==0 ); /* Otherwise useTempTable is true */
69297
- sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regTrigRowid);
69882
+ if( useTempTable ){
69883
+ sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regTrigRowid);
69884
+ }else{
69885
+ assert( pSelect==0 ); /* Otherwise useTempTable is true */
69886
+ sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regTrigRowid);
69887
+ }
6929869888
j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regTrigRowid);
6929969889
sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
6930069890
sqlite3VdbeJumpHere(v, j1);
6930169891
sqlite3VdbeAddOp1(v, OP_MustBeInt, regTrigRowid);
6930269892
}
@@ -69366,11 +69956,11 @@
6936669956
sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
6936769957
}else{
6936869958
VdbeOp *pOp;
6936969959
sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
6937069960
pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
69371
- if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
69961
+ if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
6937269962
appendFlag = 1;
6937369963
pOp->opcode = OP_NewRowid;
6937469964
pOp->p1 = baseCur;
6937569965
pOp->p2 = regRowid;
6937669966
pOp->p3 = regAutoinc;
@@ -69446,31 +70036,18 @@
6944670036
sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
6944770037
(const char*)pTab->pVtab, P4_VTAB);
6944870038
}else
6944970039
#endif
6945070040
{
69451
- sqlite3GenerateConstraintChecks(
69452
- pParse,
69453
- pTab,
69454
- baseCur,
69455
- regIns,
69456
- aRegIdx,
69457
- keyColumn>=0,
69458
- 0,
69459
- onError,
69460
- endOfLoop
70041
+ int isReplace; /* Set to true if constraints may cause a replace */
70042
+ sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
70043
+ keyColumn>=0, 0, onError, endOfLoop, &isReplace
6946170044
);
6946270045
sqlite3CompleteInsertion(
69463
- pParse,
69464
- pTab,
69465
- baseCur,
69466
- regIns,
69467
- aRegIdx,
69468
- 0,
69469
- (tmask&TRIGGER_AFTER) ? newIdx : -1,
69470
- appendFlag
69471
- );
70046
+ pParse, pTab, baseCur, regIns, aRegIdx, 0,
70047
+ (tmask&TRIGGER_AFTER) ? newIdx : -1, appendFlag, isReplace==0
70048
+ );
6947270049
}
6947370050
}
6947470051
6947570052
/* Update the count of rows that are inserted
6947670053
*/
@@ -69616,22 +70193,23 @@
6961670193
int regRowid, /* Index of the range of input registers */
6961770194
int *aRegIdx, /* Register used by each index. 0 for unused indices */
6961870195
int rowidChng, /* True if the rowid might collide with existing entry */
6961970196
int isUpdate, /* True for UPDATE, False for INSERT */
6962070197
int overrideError, /* Override onError to this if not OE_Default */
69621
- int ignoreDest /* Jump to this label on an OE_Ignore resolution */
70198
+ int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
70199
+ int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
6962270200
){
69623
- int i;
69624
- Vdbe *v;
69625
- int nCol;
69626
- int onError;
70201
+ int i; /* loop counter */
70202
+ Vdbe *v; /* VDBE under constrution */
70203
+ int nCol; /* Number of columns */
70204
+ int onError; /* Conflict resolution strategy */
6962770205
int j1; /* Addresss of jump instruction */
6962870206
int j2 = 0, j3; /* Addresses of jump instructions */
6962970207
int regData; /* Register containing first data column */
69630
- int iCur;
69631
- Index *pIdx;
69632
- int seenReplace = 0;
70208
+ int iCur; /* Table cursor number */
70209
+ Index *pIdx; /* Pointer to one of the indices */
70210
+ int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
6963370211
int hasTwoRowids = (isUpdate && rowidChng);
6963470212
6963570213
v = sqlite3GetVdbe(pParse);
6963670214
assert( v!=0 );
6963770215
assert( pTab->pSelect==0 ); /* This table is not a VIEW */
@@ -69671,11 +70249,12 @@
6967170249
}
6967270250
case OE_Ignore: {
6967370251
sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
6967470252
break;
6967570253
}
69676
- case OE_Replace: {
70254
+ default: {
70255
+ assert( onError==OE_Replace );
6967770256
j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
6967870257
sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
6967970258
sqlite3VdbeJumpHere(v, j1);
6968070259
break;
6968170260
}
@@ -69768,15 +70347,17 @@
6976870347
}
6976970348
sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
6977070349
sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
6977170350
sqlite3IndexAffinityStr(v, pIdx);
6977270351
sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
69773
- sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
6977470352
6977570353
/* Find out what action to take in case there is an indexing conflict */
6977670354
onError = pIdx->onError;
69777
- if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
70355
+ if( onError==OE_None ){
70356
+ sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
70357
+ continue; /* pIdx is not a UNIQUE index */
70358
+ }
6977870359
if( overrideError!=OE_Default ){
6977970360
onError = overrideError;
6978070361
}else if( onError==OE_Default ){
6978170362
onError = OE_Abort;
6978270363
}
@@ -69785,65 +70366,64 @@
6978570366
else if( onError==OE_Fail ) onError = OE_Abort;
6978670367
}
6978770368
6978870369
6978970370
/* Check to see if the new index entry will be unique */
69790
- j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
6979170371
regR = sqlite3GetTempReg(pParse);
6979270372
sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
6979370373
j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
69794
- regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]),
70374
+ regR, SQLITE_INT_TO_PTR(regIdx),
6979570375
P4_INT32);
70376
+ sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
6979670377
6979770378
/* Generate code that executes if the new index entry is not unique */
6979870379
assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
6979970380
|| onError==OE_Ignore || onError==OE_Replace );
6980070381
switch( onError ){
6980170382
case OE_Rollback:
6980270383
case OE_Abort:
6980370384
case OE_Fail: {
69804
- int j, n1, n2;
69805
- char zErrMsg[200];
69806
- sqlite3_snprintf(ArraySize(zErrMsg), zErrMsg,
69807
- pIdx->nColumn>1 ? "columns " : "column ");
69808
- n1 = sqlite3Strlen30(zErrMsg);
69809
- for(j=0; j<pIdx->nColumn && n1<ArraySize(zErrMsg)-30; j++){
70385
+ int j;
70386
+ StrAccum errMsg;
70387
+ const char *zSep;
70388
+ char *zErr;
70389
+
70390
+ sqlite3StrAccumInit(&errMsg, 0, 0, 200);
70391
+ errMsg.db = pParse->db;
70392
+ zSep = pIdx->nColumn>1 ? "columns " : "column ";
70393
+ for(j=0; j<pIdx->nColumn; j++){
6981070394
char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
69811
- n2 = sqlite3Strlen30(zCol);
69812
- if( j>0 ){
69813
- sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], ", ");
69814
- n1 += 2;
69815
- }
69816
- if( n1+n2>ArraySize(zErrMsg)-30 ){
69817
- sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "...");
69818
- n1 += 3;
69819
- break;
69820
- }else{
69821
- sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
69822
- n1 += n2;
69823
- }
69824
- }
69825
- sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1],
69826
- pIdx->nColumn>1 ? " are not unique" : " is not unique");
69827
- sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
70395
+ sqlite3StrAccumAppend(&errMsg, zSep, -1);
70396
+ zSep = ", ";
70397
+ sqlite3StrAccumAppend(&errMsg, zCol, -1);
70398
+ }
70399
+ sqlite3StrAccumAppend(&errMsg,
70400
+ pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
70401
+ zErr = sqlite3StrAccumFinish(&errMsg);
70402
+ sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErr, 0);
70403
+ sqlite3DbFree(errMsg.db, zErr);
6982870404
break;
6982970405
}
6983070406
case OE_Ignore: {
6983170407
assert( seenReplace==0 );
6983270408
sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
6983370409
break;
6983470410
}
69835
- case OE_Replace: {
70411
+ default: {
70412
+ assert( onError==OE_Replace );
6983670413
sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
6983770414
seenReplace = 1;
6983870415
break;
6983970416
}
6984070417
}
69841
- sqlite3VdbeJumpHere(v, j2);
6984270418
sqlite3VdbeJumpHere(v, j3);
6984370419
sqlite3ReleaseTempReg(pParse, regR);
6984470420
}
70421
+
70422
+ if( pbMayReplace ){
70423
+ *pbMayReplace = seenReplace;
70424
+ }
6984570425
}
6984670426
6984770427
/*
6984870428
** This routine generates code to finish the INSERT or UPDATE operation
6984970429
** that was started by a prior call to sqlite3GenerateConstraintChecks.
@@ -69859,11 +70439,12 @@
6985970439
int baseCur, /* Index of a read/write cursor pointing at pTab */
6986070440
int regRowid, /* Range of content */
6986170441
int *aRegIdx, /* Register used by each index. 0 for unused indices */
6986270442
int isUpdate, /* True for UPDATE, False for INSERT */
6986370443
int newIdx, /* Index of NEW table for triggers. -1 if none */
69864
- int appendBias /* True if this is likely to be an append */
70444
+ int appendBias, /* True if this is likely to be an append */
70445
+ int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
6986570446
){
6986670447
int i;
6986770448
Vdbe *v;
6986870449
int nIdx;
6986970450
Index *pIdx;
@@ -69876,10 +70457,13 @@
6987670457
assert( pTab->pSelect==0 ); /* This table is not a VIEW */
6987770458
for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
6987870459
for(i=nIdx-1; i>=0; i--){
6987970460
if( aRegIdx[i]==0 ) continue;
6988070461
sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
70462
+ if( useSeekResult ){
70463
+ sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
70464
+ }
6988170465
}
6988270466
regData = regRowid + 1;
6988370467
regRec = sqlite3GetTempReg(pParse);
6988470468
sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
6988570469
sqlite3TableAffinityStr(v, pTab);
@@ -69896,10 +70480,13 @@
6989670480
pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
6989770481
}
6989870482
if( appendBias ){
6989970483
pik_flags |= OPFLAG_APPEND;
6990070484
}
70485
+ if( useSeekResult ){
70486
+ pik_flags |= OPFLAG_USESEEKRESULT;
70487
+ }
6990170488
sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
6990270489
if( !pParse->nested ){
6990370490
sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
6990470491
}
6990570492
sqlite3VdbeChangeP5(v, pik_flags);
@@ -69933,11 +70520,11 @@
6993370520
assert( pIdx->pSchema==pTab->pSchema );
6993470521
sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
6993570522
(char*)pKey, P4_KEYINFO_HANDOFF);
6993670523
VdbeComment((v, "%s", pIdx->zName));
6993770524
}
69938
- if( pParse->nTab<=baseCur+i ){
70525
+ if( pParse->nTab<baseCur+i ){
6993970526
pParse->nTab = baseCur+i;
6994070527
}
6994170528
return i-1;
6994270529
}
6994370530
@@ -69993,11 +70580,11 @@
6999370580
return 0; /* Different columns indexed */
6999470581
}
6999570582
if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
6999670583
return 0; /* Different sort orders */
6999770584
}
69998
- if( pSrc->azColl[i]!=pDest->azColl[i] ){
70585
+ if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
6999970586
return 0; /* Different collating sequences */
7000070587
}
7000170588
}
7000270589
7000370590
/* If no test above fails then the indices must be compatible */
@@ -70224,11 +70811,11 @@
7022470811
sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
7022570812
sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
7022670813
sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
7022770814
autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
7022870815
for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
70229
- for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
70816
+ for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
7023070817
if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
7023170818
}
7023270819
assert( pSrcIdx );
7023370820
sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
7023470821
sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
@@ -70283,11 +70870,11 @@
7028370870
** Main file for the SQLite library. The routines in this file
7028470871
** implement the programmer interface to the library. Routines in
7028570872
** other files are for internal use by SQLite and should not be
7028670873
** accessed by users of the library.
7028770874
**
70288
-** $Id: legacy.c,v 1.32 2009/03/19 18:51:07 danielk1977 Exp $
70875
+** $Id: legacy.c,v 1.33 2009/05/05 20:02:48 drh Exp $
7028970876
*/
7029070877
7029170878
7029270879
/*
7029370880
** Execute SQL code. Return one of the SQLITE_ success/failure
@@ -70304,17 +70891,16 @@
7030470891
const char *zSql, /* The SQL to be executed */
7030570892
sqlite3_callback xCallback, /* Invoke this callback routine */
7030670893
void *pArg, /* First argument to xCallback() */
7030770894
char **pzErrMsg /* Write error messages here */
7030870895
){
70309
- int rc = SQLITE_OK;
70310
- const char *zLeftover;
70311
- sqlite3_stmt *pStmt = 0;
70312
- char **azCols = 0;
70313
-
70314
- int nRetry = 0;
70315
- int nCallback;
70896
+ int rc = SQLITE_OK; /* Return code */
70897
+ const char *zLeftover; /* Tail of unprocessed SQL */
70898
+ sqlite3_stmt *pStmt = 0; /* The current SQL statement */
70899
+ char **azCols = 0; /* Names of result columns */
70900
+ int nRetry = 0; /* Number of retry attempts */
70901
+ int callbackIsInit; /* True if callback data is initialized */
7031670902
7031770903
if( zSql==0 ) zSql = "";
7031870904
7031970905
sqlite3_mutex_enter(db->mutex);
7032070906
sqlite3Error(db, SQLITE_OK, 0);
@@ -70332,34 +70918,33 @@
7033270918
/* this happens for a comment or white-space */
7033370919
zSql = zLeftover;
7033470920
continue;
7033570921
}
7033670922
70337
- nCallback = 0;
70923
+ callbackIsInit = 0;
7033870924
nCol = sqlite3_column_count(pStmt);
7033970925
7034070926
while( 1 ){
7034170927
int i;
7034270928
rc = sqlite3_step(pStmt);
7034370929
7034470930
/* Invoke the callback function if required */
7034570931
if( xCallback && (SQLITE_ROW==rc ||
70346
- (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){
70347
- if( 0==nCallback ){
70932
+ (SQLITE_DONE==rc && !callbackIsInit
70933
+ && db->flags&SQLITE_NullCallback)) ){
70934
+ if( !callbackIsInit ){
70935
+ azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
7034870936
if( azCols==0 ){
70349
- azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
70350
- if( azCols==0 ){
70351
- goto exec_out;
70352
- }
70937
+ goto exec_out;
7035370938
}
7035470939
for(i=0; i<nCol; i++){
7035570940
azCols[i] = (char *)sqlite3_column_name(pStmt, i);
7035670941
/* sqlite3VdbeSetColName() installs column names as UTF8
7035770942
** strings so there is no way for sqlite3_column_name() to fail. */
7035870943
assert( azCols[i]!=0 );
7035970944
}
70360
- nCallback++;
70945
+ callbackIsInit = 1;
7036170946
}
7036270947
if( rc==SQLITE_ROW ){
7036370948
azVals = &azCols[nCol];
7036470949
for(i=0; i<nCol; i++){
7036570950
azVals[i] = (char *)sqlite3_column_text(pStmt, i);
@@ -70397,11 +70982,11 @@
7039770982
exec_out:
7039870983
if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
7039970984
sqlite3DbFree(db, azCols);
7040070985
7040170986
rc = sqlite3ApiExit(db, rc);
70402
- if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
70987
+ if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
7040370988
int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
7040470989
*pzErrMsg = sqlite3Malloc(nErrMsg);
7040570990
if( *pzErrMsg ){
7040670991
memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
7040770992
}
@@ -72848,11 +73433,11 @@
7284873433
*************************************************************************
7284973434
** This file contains the implementation of the sqlite3_prepare()
7285073435
** interface, and routines that contribute to loading the database schema
7285173436
** from disk.
7285273437
**
72853
-** $Id: prepare.c,v 1.116 2009/04/02 18:32:27 drh Exp $
73438
+** $Id: prepare.c,v 1.117 2009/04/20 17:43:03 drh Exp $
7285473439
*/
7285573440
7285673441
/*
7285773442
** Fill the InitData structure with an error message that indicates
7285873443
** that the database is corrupt.
@@ -72961,10 +73546,11 @@
7296173546
** auxiliary databases. Return one of the SQLITE_ error codes to
7296273547
** indicate success or failure.
7296373548
*/
7296473549
static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
7296573550
int rc;
73551
+ int i;
7296673552
BtCursor *curMain;
7296773553
int size;
7296873554
Table *pTab;
7296973555
Db *pDb;
7297073556
char const *azArg[4];
@@ -73050,11 +73636,12 @@
7305073636
rc = SQLITE_NOMEM;
7305173637
goto error_out;
7305273638
}
7305373639
sqlite3BtreeEnter(pDb->pBt);
7305473640
rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, curMain);
73055
- if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
73641
+ if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
73642
+ if( rc!=SQLITE_OK ){
7305673643
sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
7305773644
goto initone_error_out;
7305873645
}
7305973646
7306073647
/* Get the database meta information.
@@ -73072,21 +73659,16 @@
7307273659
** meta[9]
7307373660
**
7307473661
** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
7307573662
** the possible values of meta[4].
7307673663
*/
73077
- if( rc==SQLITE_OK ){
73078
- int i;
73079
- for(i=0; i<ArraySize(meta); i++){
73080
- rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
73081
- if( rc ){
73082
- sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
73083
- goto initone_error_out;
73084
- }
73085
- }
73086
- }else{
73087
- memset(meta, 0, sizeof(meta));
73664
+ for(i=0; i<ArraySize(meta); i++){
73665
+ rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
73666
+ if( rc ){
73667
+ sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
73668
+ goto initone_error_out;
73669
+ }
7308873670
}
7308973671
pDb->pSchema->schema_cookie = meta[0];
7309073672
7309173673
/* If opening a non-empty database, check the text encoding. For the
7309273674
** main database, set sqlite3.enc to the encoding of the main database.
@@ -73683,11 +74265,11 @@
7368374265
**
7368474266
*************************************************************************
7368574267
** This file contains C code routines that are called by the parser
7368674268
** to handle SELECT statements in SQLite.
7368774269
**
73688
-** $Id: select.c,v 1.507 2009/04/02 16:59:47 drh Exp $
74270
+** $Id: select.c,v 1.512 2009/05/03 20:23:54 drh Exp $
7368974271
*/
7369074272
7369174273
7369274274
/*
7369374275
** Delete all the content of a Select structure but do not deallocate
@@ -73863,46 +74445,11 @@
7386374445
*/
7386474446
static void setToken(Token *p, const char *z){
7386574447
p->z = (u8*)z;
7386674448
p->n = z ? sqlite3Strlen30(z) : 0;
7386774449
p->dyn = 0;
73868
-}
73869
-
73870
-/*
73871
-** Set the token to the double-quoted and escaped version of the string pointed
73872
-** to by z. For example;
73873
-**
73874
-** {a"bc} -> {"a""bc"}
73875
-*/
73876
-static void setQuotedToken(Parse *pParse, Token *p, const char *z){
73877
-
73878
- /* Check if the string appears to be quoted using "..." or `...`
73879
- ** or [...] or '...' or if the string contains any " characters.
73880
- ** If it does, then record a version of the string with the special
73881
- ** characters escaped.
73882
- */
73883
- const char *z2 = z;
73884
- if( *z2!='[' && *z2!='`' && *z2!='\'' ){
73885
- while( *z2 ){
73886
- if( *z2=='"' ) break;
73887
- z2++;
73888
- }
73889
- }
73890
-
73891
- if( *z2 ){
73892
- /* String contains " characters - copy and quote the string. */
73893
- p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
73894
- if( p->z ){
73895
- p->n = sqlite3Strlen30((char *)p->z);
73896
- p->dyn = 1;
73897
- }
73898
- }else{
73899
- /* String contains no " characters - copy the pointer. */
73900
- p->z = (u8*)z;
73901
- p->n = (int)(z2 - z);
73902
- p->dyn = 0;
73903
- }
74450
+ p->quoted = 0;
7390474451
}
7390574452
7390674453
/*
7390774454
** Create an expression node for an identifier with the name of zName
7390874455
*/
@@ -74091,10 +74638,11 @@
7409174638
){
7409274639
Vdbe *v = pParse->pVdbe;
7409374640
int nExpr = pOrderBy->nExpr;
7409474641
int regBase = sqlite3GetTempRange(pParse, nExpr+2);
7409574642
int regRecord = sqlite3GetTempReg(pParse);
74643
+ sqlite3ExprCacheClear(pParse);
7409674644
sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
7409774645
sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
7409874646
sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
7409974647
sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
7410074648
sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
@@ -74243,10 +74791,11 @@
7424374791
}
7424474792
}else if( eDest!=SRT_Exists ){
7424574793
/* If the destination is an EXISTS(...) expression, the actual
7424674794
** values returned by the SELECT are not required.
7424774795
*/
74796
+ sqlite3ExprCacheClear(pParse);
7424874797
sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
7424974798
}
7425074799
nColumn = nResultCol;
7425174800
7425274801
/* If the DISTINCT keyword was present on the SELECT statement
@@ -74860,11 +75409,10 @@
7486075409
}
7486175410
if( db->mallocFailed ){
7486275411
sqlite3DbFree(db, zName);
7486375412
break;
7486475413
}
74865
- sqlite3Dequote(zName);
7486675414
7486775415
/* Make sure the column name is unique. If the name is not unique,
7486875416
** append a integer to the name so that it becomes unique.
7486975417
*/
7487075418
nName = sqlite3Strlen30(zName);
@@ -75016,10 +75564,11 @@
7501675564
** "LIMIT -1" always shows all rows. There is some
7501775565
** contraversy about what the correct behavior should be.
7501875566
** The current implementation interprets "LIMIT 0" to mean
7501975567
** no rows.
7502075568
*/
75569
+ sqlite3ExprCacheClear(pParse);
7502175570
if( p->pLimit ){
7502275571
p->iLimit = iLimit = ++pParse->nMem;
7502375572
v = sqlite3GetVdbe(pParse);
7502475573
if( v==0 ) return;
7502575574
sqlite3ExprCode(pParse, p->pLimit, iLimit);
@@ -75064,11 +75613,12 @@
7506475613
if( p->pPrior ){
7506575614
pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
7506675615
}else{
7506775616
pRet = 0;
7506875617
}
75069
- if( pRet==0 ){
75618
+ assert( iCol>=0 );
75619
+ if( pRet==0 && iCol<p->pEList->nExpr ){
7507075620
pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
7507175621
}
7507275622
return pRet;
7507375623
}
7507475624
#endif /* SQLITE_OMIT_COMPOUND_SELECT */
@@ -75771,11 +76321,11 @@
7577176321
}
7577276322
}
7577376323
}
7577476324
7577576325
/* Compute the comparison permutation and keyinfo that is used with
75776
- ** the permutation in order to comparisons to determine if the next
76326
+ ** the permutation used to determine if the next
7577776327
** row of results comes from selectA or selectB. Also add explicit
7577876328
** collations to the ORDER BY clause terms so that when the subqueries
7577976329
** to the right and the left are evaluated, they use the correct
7578076330
** collation.
7578176331
*/
@@ -76894,16 +77444,16 @@
7689477444
continue;
7689577445
}
7689677446
}
7689777447
pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
7689877448
if( pRight==0 ) break;
76899
- setQuotedToken(pParse, &pRight->token, zName);
77449
+ setToken(&pRight->token, zName);
7690077450
if( longNames || pTabList->nSrc>1 ){
7690177451
Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
7690277452
pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
7690377453
if( pExpr==0 ) break;
76904
- setQuotedToken(pParse, &pLeft->token, zTabName);
77454
+ setToken(&pLeft->token, zTabName);
7690577455
setToken(&pExpr->span,
7690677456
sqlite3MPrintf(db, "%s.%s", zTabName, zName));
7690777457
pExpr->span.dyn = 1;
7690877458
pExpr->token.z = 0;
7690977459
pExpr->token.n = 0;
@@ -77125,10 +77675,11 @@
7712577675
int i;
7712677676
struct AggInfo_func *pF;
7712777677
struct AggInfo_col *pC;
7712877678
7712977679
pAggInfo->directMode = 1;
77680
+ sqlite3ExprCacheClear(pParse);
7713077681
for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
7713177682
int nArg;
7713277683
int addrNext = 0;
7713377684
int regAgg;
7713477685
ExprList *pList = pF->pExpr->x.pList;
@@ -77164,16 +77715,18 @@
7716477715
sqlite3VdbeChangeP5(v, (u8)nArg);
7716577716
sqlite3ReleaseTempRange(pParse, regAgg, nArg);
7716677717
sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
7716777718
if( addrNext ){
7716877719
sqlite3VdbeResolveLabel(v, addrNext);
77720
+ sqlite3ExprCacheClear(pParse);
7716977721
}
7717077722
}
7717177723
for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
7717277724
sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
7717377725
}
7717477726
pAggInfo->directMode = 0;
77727
+ sqlite3ExprCacheClear(pParse);
7717577728
}
7717677729
7717777730
/*
7717877731
** Generate code for the SELECT statement given in the p argument.
7717977732
**
@@ -77434,11 +77987,11 @@
7743477987
/* Aggregate and non-aggregate queries are handled differently */
7743577988
if( !isAgg && pGroupBy==0 ){
7743677989
/* This case is for non-aggregate queries
7743777990
** Begin the database scan
7743877991
*/
77439
- pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0, 0);
77992
+ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
7744077993
if( pWInfo==0 ) goto select_end;
7744177994
7744277995
/* If sorting index that was created by a prior OP_OpenEphemeral
7744377996
** instruction ended up not being needed, then change the OP_OpenEphemeral
7744477997
** into an OP_Noop.
@@ -77556,11 +78109,11 @@
7755678109
** This might involve two separate loops with an OP_Sort in between, or
7755778110
** it might be a single loop that uses an index to extract information
7755878111
** in the right order to begin with.
7755978112
*/
7756078113
sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
77561
- pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0);
78114
+ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
7756278115
if( pWInfo==0 ) goto select_end;
7756378116
if( pGroupBy==0 ){
7756478117
/* The optimizer is able to deliver rows in group by order so
7756578118
** we do not have to sort. The OP_OpenEphemeral table will be
7756678119
** cancelled later because we still need to use the pKeyInfo
@@ -77587,10 +78140,11 @@
7758778140
nCol++;
7758878141
j++;
7758978142
}
7759078143
}
7759178144
regBase = sqlite3GetTempRange(pParse, nCol);
78145
+ sqlite3ExprCacheClear(pParse);
7759278146
sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
7759378147
sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
7759478148
j = nGroupBy+1;
7759578149
for(i=0; i<sAggInfo.nColumn; i++){
7759678150
struct AggInfo_col *pCol = &sAggInfo.aCol[i];
@@ -77613,18 +78167,20 @@
7761378167
sqlite3ReleaseTempRange(pParse, regBase, nCol);
7761478168
sqlite3WhereEnd(pWInfo);
7761578169
sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
7761678170
VdbeComment((v, "GROUP BY sort"));
7761778171
sAggInfo.useSortingIdx = 1;
78172
+ sqlite3ExprCacheClear(pParse);
7761878173
}
7761978174
7762078175
/* Evaluate the current GROUP BY terms and store in b0, b1, b2...
7762178176
** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
7762278177
** Then compare the current GROUP BY terms against the GROUP BY terms
7762378178
** from the previous row currently stored in a0, a1, a2...
7762478179
*/
7762578180
addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
78181
+ sqlite3ExprCacheClear(pParse);
7762678182
for(j=0; j<pGroupBy->nExpr; j++){
7762778183
if( groupBySort ){
7762878184
sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
7762978185
}else{
7763078186
sAggInfo.directMode = 1;
@@ -77811,11 +78367,11 @@
7781178367
/* This case runs if the aggregate has no GROUP BY clause. The
7781278368
** processing is much simpler since there is only a single row
7781378369
** of output.
7781478370
*/
7781578371
resetAccumulator(pParse, &sAggInfo);
77816
- pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag, 0);
78372
+ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
7781778373
if( pWInfo==0 ){
7781878374
sqlite3ExprListDelete(db, pDel);
7781978375
goto select_end;
7782078376
}
7782178377
updateAccumulator(pParse, &sAggInfo);
@@ -78179,11 +78735,11 @@
7817978735
** May you share freely, never taking more than you give.
7818078736
**
7818178737
*************************************************************************
7818278738
**
7818378739
**
78184
-** $Id: trigger.c,v 1.135 2009/02/28 10:47:42 danielk1977 Exp $
78740
+** $Id: trigger.c,v 1.138 2009/05/06 18:42:21 drh Exp $
7818578741
*/
7818678742
7818778743
#ifndef SQLITE_OMIT_TRIGGER
7818878744
/*
7818978745
** Delete a linked list of TriggerStep structures.
@@ -78453,11 +79009,11 @@
7845379009
pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
7845479010
if( pTrig ){
7845579011
db->mallocFailed = 1;
7845679012
}else if( pLink->pSchema==pLink->pTabSchema ){
7845779013
Table *pTab;
78458
- int n = sqlite3Strlen30(pLink->table) + 1;
79014
+ int n = sqlite3Strlen30(pLink->table);
7845979015
pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
7846079016
assert( pTab!=0 );
7846179017
pLink->pNext = pTab->pTrigger;
7846279018
pTab->pTrigger = pLink;
7846379019
}
@@ -78680,11 +79236,11 @@
7868079236
/*
7868179237
** Return a pointer to the Table structure for the table that a trigger
7868279238
** is set on.
7868379239
*/
7868479240
static Table *tableOfTrigger(Trigger *pTrigger){
78685
- int n = sqlite3Strlen30(pTrigger->table) + 1;
79241
+ int n = sqlite3Strlen30(pTrigger->table);
7868679242
return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
7868779243
}
7868879244
7868979245
7869079246
/*
@@ -78831,10 +79387,11 @@
7883179387
iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
7883279388
if( iDb==0 || iDb>=2 ){
7883379389
assert( iDb<pParse->db->nDb );
7883479390
sDb.z = (u8*)pParse->db->aDb[iDb].zName;
7883579391
sDb.n = sqlite3Strlen30((char*)sDb.z);
79392
+ sDb.quoted = 0;
7883679393
pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target);
7883779394
} else {
7883879395
pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
7883979396
}
7884079397
return pSrc;
@@ -78857,11 +79414,11 @@
7885779414
assert( pTriggerStep!=0 );
7885879415
assert( v!=0 );
7885979416
sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0);
7886079417
VdbeComment((v, "begin trigger %s", pStepList->pTrig->name));
7886179418
while( pTriggerStep ){
78862
- sqlite3ExprClearColumnCache(pParse, -1);
79419
+ sqlite3ExprCacheClear(pParse);
7886379420
orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
7886479421
pParse->trigStack->orconf = orconf;
7886579422
switch( pTriggerStep->op ){
7886679423
case TK_SELECT: {
7886779424
Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect, 0);
@@ -79056,11 +79613,11 @@
7905679613
**
7905779614
*************************************************************************
7905879615
** This file contains C code routines that are called by the parser
7905979616
** to handle UPDATE statements.
7906079617
**
79061
-** $Id: update.c,v 1.196 2009/02/28 10:47:42 danielk1977 Exp $
79618
+** $Id: update.c,v 1.200 2009/05/05 15:46:10 drh Exp $
7906279619
*/
7906379620
7906479621
#ifndef SQLITE_OMIT_VIRTUALTABLE
7906579622
/* Forward declaration */
7906679623
static void updateVirtualTable(
@@ -79098,11 +79655,12 @@
7909879655
** the column is a literal number, string or null. The sqlite3ValueFromExpr()
7909979656
** function is capable of transforming these types of expressions into
7910079657
** sqlite3_value objects.
7910179658
*/
7910279659
SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
79103
- if( pTab && !pTab->pSelect ){
79660
+ assert( pTab!=0 );
79661
+ if( !pTab->pSelect ){
7910479662
sqlite3_value *pValue;
7910579663
u8 enc = ENC(sqlite3VdbeDb(v));
7910679664
Column *pCol = &pTab->aCol[i];
7910779665
VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
7910879666
assert( i<pTab->nCol );
@@ -79388,18 +79946,17 @@
7938879946
}
7938979947
7939079948
/* Begin the database scan
7939179949
*/
7939279950
sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
79393
- pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
79394
- WHERE_ONEPASS_DESIRED, 0);
79951
+ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
7939579952
if( pWInfo==0 ) goto update_cleanup;
7939679953
okOnePass = pWInfo->okOnePass;
7939779954
7939879955
/* Remember the rowid of every item to be updated.
7939979956
*/
79400
- sqlite3VdbeAddOp2(v, IsVirtual(pTab)?OP_VRowid:OP_Rowid, iCur, regOldRowid);
79957
+ sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
7940179958
if( !okOnePass ){
7940279959
regRowSet = ++pParse->nMem;
7940379960
sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
7940479961
}
7940579962
@@ -79412,11 +79969,11 @@
7941279969
if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
7941379970
regRowCount = ++pParse->nMem;
7941479971
sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
7941579972
}
7941679973
79417
- if( !isView && !IsVirtual(pTab) ){
79974
+ if( !isView ){
7941879975
/*
7941979976
** Open every index that needs updating. Note that if any
7942079977
** index could potentially invoke a REPLACE conflict resolution
7942179978
** action, then we need to open all indices because we might need
7942279979
** to be deleting some records.
@@ -79491,11 +80048,11 @@
7949180048
if( i==pTab->iPKey ){
7949280049
sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
7949380050
continue;
7949480051
}
7949580052
j = aXRef[i];
79496
- if( new_col_mask&((u32)1<<i) || new_col_mask==0xffffffff ){
80053
+ if( (i<32 && (new_col_mask&((u32)1<<i))!=0) || new_col_mask==0xffffffff ){
7949780054
if( j<0 ){
7949880055
sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regCols+i);
7949980056
sqlite3ColumnDefault(v, pTab, i);
7950080057
}else{
7950180058
sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr, regCols+i);
@@ -79517,11 +80074,11 @@
7951780074
7951880075
sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
7951980076
sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
7952080077
}
7952180078
79522
- if( !isView && !IsVirtual(pTab) ){
80079
+ if( !isView ){
7952380080
/* Loop over every record that needs updating. We have to load
7952480081
** the old data for each record to be updated because some columns
7952580082
** might not change and we will need to copy the old value.
7952680083
** Also, the old data is needed to delete the old index entries.
7952780084
** So make the cursor point at the old record.
@@ -79555,11 +80112,11 @@
7955580112
7955680113
/* Do constraint checks
7955780114
*/
7955880115
sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
7955980116
aRegIdx, chngRowid, 1,
79560
- onError, addr);
80117
+ onError, addr, 0);
7956180118
7956280119
/* Delete the old indices for the current record.
7956380120
*/
7956480121
j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
7956580122
sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
@@ -79572,11 +80129,11 @@
7957280129
sqlite3VdbeJumpHere(v, j1);
7957380130
7957480131
/* Create the new index entries and the new record.
7957580132
*/
7957680133
sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid,
79577
- aRegIdx, 1, -1, 0);
80134
+ aRegIdx, 1, -1, 0, 0);
7957880135
}
7957980136
7958080137
/* Increment the row counter
7958180138
*/
7958280139
if( db->flags & SQLITE_CountRows && !pParse->trigStack){
@@ -79745,26 +80302,28 @@
7974580302
** This file contains code used to implement the VACUUM command.
7974680303
**
7974780304
** Most of the code in this file may be omitted by defining the
7974880305
** SQLITE_OMIT_VACUUM macro.
7974980306
**
79750
-** $Id: vacuum.c,v 1.87 2009/04/02 20:16:59 drh Exp $
80307
+** $Id: vacuum.c,v 1.88 2009/05/05 17:37:23 drh Exp $
7975180308
*/
7975280309
7975380310
#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
7975480311
/*
7975580312
** Execute zSql on database db. Return an error code.
7975680313
*/
7975780314
static int execSql(sqlite3 *db, const char *zSql){
7975880315
sqlite3_stmt *pStmt;
80316
+ VVA_ONLY( int rc; )
7975980317
if( !zSql ){
7976080318
return SQLITE_NOMEM;
7976180319
}
7976280320
if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
7976380321
return sqlite3_errcode(db);
7976480322
}
79765
- while( SQLITE_ROW==sqlite3_step(pStmt) ){}
80323
+ VVA_ONLY( rc = ) sqlite3_step(pStmt);
80324
+ assert( rc!=SQLITE_ROW );
7976680325
return sqlite3_finalize(pStmt);
7976780326
}
7976880327
7976980328
/*
7977080329
** Execute zSql on database db. The statement returns exactly
@@ -79871,11 +80430,11 @@
7987180430
}
7987280431
#endif
7987380432
7987480433
if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
7987580434
|| (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
79876
- || db->mallocFailed
80435
+ || NEVER(db->mallocFailed)
7987780436
){
7987880437
rc = SQLITE_NOMEM;
7987980438
goto end_of_vacuum;
7988080439
}
7988180440
rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
@@ -79959,11 +80518,11 @@
7995980518
** call to sqlite3BtreeCopyFile(). The main database btree level
7996080519
** transaction is then committed, so the SQL level never knows it was
7996180520
** opened for writing. This way, the SQL transaction used to create the
7996280521
** temporary database never needs to be committed.
7996380522
*/
79964
- if( rc==SQLITE_OK ){
80523
+ {
7996580524
u32 meta;
7996680525
int i;
7996780526
7996880527
/* This array determines which meta meta values are preserved in the
7996980528
** vacuum. Even entries are the meta value number and odd entries
@@ -79981,14 +80540,16 @@
7998180540
assert( 1==sqlite3BtreeIsInTrans(pTemp) );
7998280541
assert( 1==sqlite3BtreeIsInTrans(pMain) );
7998380542
7998480543
/* Copy Btree meta values */
7998580544
for(i=0; i<ArraySize(aCopy); i+=2){
80545
+ /* GetMeta() and UpdateMeta() cannot fail in this context because
80546
+ ** we already have page 1 loaded into cache and marked dirty. */
7998680547
rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
79987
- if( rc!=SQLITE_OK ) goto end_of_vacuum;
80548
+ if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
7998880549
rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
79989
- if( rc!=SQLITE_OK ) goto end_of_vacuum;
80550
+ if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
7999080551
}
7999180552
7999280553
rc = sqlite3BtreeCopyFile(pMain, pTemp);
7999380554
if( rc!=SQLITE_OK ) goto end_of_vacuum;
7999480555
rc = sqlite3BtreeCommit(pTemp);
@@ -79996,13 +80557,12 @@
7999680557
#ifndef SQLITE_OMIT_AUTOVACUUM
7999780558
sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
7999880559
#endif
7999980560
}
8000080561
80001
- if( rc==SQLITE_OK ){
80002
- rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
80003
- }
80562
+ assert( rc==SQLITE_OK );
80563
+ rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
8000480564
8000580565
end_of_vacuum:
8000680566
/* Restore the original value of db->flags */
8000780567
db->flags = saved_flags;
8000880568
db->nChange = saved_nChange;
@@ -80042,11 +80602,11 @@
8004280602
** May you share freely, never taking more than you give.
8004380603
**
8004480604
*************************************************************************
8004580605
** This file contains code used to help implement virtual tables.
8004680606
**
80047
-** $Id: vtab.c,v 1.85 2009/04/11 16:27:20 drh Exp $
80607
+** $Id: vtab.c,v 1.86 2009/04/28 13:01:09 drh Exp $
8004880608
*/
8004980609
#ifndef SQLITE_OMIT_VIRTUALTABLE
8005080610
8005180611
/*
8005280612
** The actual function that does the work of creating a new module.
@@ -80338,11 +80898,11 @@
8033880898
*/
8033980899
else {
8034080900
Table *pOld;
8034180901
Schema *pSchema = pTab->pSchema;
8034280902
const char *zName = pTab->zName;
80343
- int nName = sqlite3Strlen30(zName) + 1;
80903
+ int nName = sqlite3Strlen30(zName);
8034480904
pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
8034580905
if( pOld ){
8034680906
db->mallocFailed = 1;
8034780907
assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
8034880908
return;
@@ -80901,11 +81461,11 @@
8090181461
** generating the code that loops through a table looking for applicable
8090281462
** rows. Indices are selected and used to speed the search when doing
8090381463
** so is applicable. Because this module is responsible for selecting
8090481464
** indices, you might also think of this module as the "query optimizer".
8090581465
**
80906
-** $Id: where.c,v 1.382 2009/04/07 13:48:12 drh Exp $
81466
+** $Id: where.c,v 1.396 2009/05/06 19:03:14 drh Exp $
8090781467
*/
8090881468
8090981469
/*
8091081470
** Trace output macros
8091181471
*/
@@ -80927,14 +81487,12 @@
8092781487
typedef struct WhereCost WhereCost;
8092881488
8092981489
/*
8093081490
** The query generator uses an array of instances of this structure to
8093181491
** help it analyze the subexpressions of the WHERE clause. Each WHERE
80932
-** clause subexpression is separated from the others by AND operators.
80933
-** (Note: the same data structure is also reused to hold a group of terms
80934
-** separated by OR operators. But at the top-level, everything is AND
80935
-** separated.)
81492
+** clause subexpression is separated from the others by AND operators,
81493
+** usually, or sometimes subexpressions separated by OR.
8093681494
**
8093781495
** All WhereTerms are collected into a single WhereClause structure.
8093881496
** The following identity holds:
8093981497
**
8094081498
** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
@@ -81112,15 +81670,16 @@
8111281670
** ISNULL constraints will then not be used on the right table of a left
8111381671
** join. Tickets #2177 and #2189.
8111481672
*/
8111581673
#define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
8111681674
#define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
81117
-#define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) */
81675
+#define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */
8111881676
#define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
8111981677
#define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
81120
-#define WHERE_INDEXED 0x00070000 /* Anything that uses an index */
81121
-#define WHERE_IN_ABLE 0x00071000 /* Able to support an IN operator */
81678
+#define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */
81679
+#define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */
81680
+#define WHERE_IN_ABLE 0x000f1000 /* Able to support an IN operator */
8112281681
#define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
8112381682
#define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
8112481683
#define WHERE_IDX_ONLY 0x00800000 /* Use index only - omit table */
8112581684
#define WHERE_ORDERBY 0x01000000 /* Output will appear in correct order */
8112681685
#define WHERE_REVERSE 0x02000000 /* Scan in reverse order */
@@ -81259,20 +81818,21 @@
8125981818
whereSplit(pWC, pExpr->pRight, op);
8126081819
}
8126181820
}
8126281821
8126381822
/*
81264
-** Initialize an expression mask set
81823
+** Initialize an expression mask set (a WhereMaskSet object)
8126581824
*/
8126681825
#define initMaskSet(P) memset(P, 0, sizeof(*P))
8126781826
8126881827
/*
8126981828
** Return the bitmask for the given cursor number. Return 0 if
8127081829
** iCursor is not in the set.
8127181830
*/
8127281831
static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
8127381832
int i;
81833
+ assert( pMaskSet->n<=sizeof(Bitmask)*8 );
8127481834
for(i=0; i<pMaskSet->n; i++){
8127581835
if( pMaskSet->ix[i]==iCursor ){
8127681836
return ((Bitmask)1)<<i;
8127781837
}
8127881838
}
@@ -81510,10 +82070,11 @@
8151082070
){
8151182071
const char *z; /* String on RHS of LIKE operator */
8151282072
Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
8151382073
ExprList *pList; /* List of operands to the LIKE operator */
8151482074
int c; /* One character in z[] */
82075
+ int n; /* Length of string z[] */
8151582076
int cnt; /* Number of non-wildcard prefix characters */
8151682077
char wc[3]; /* Wildcard characters */
8151782078
CollSeq *pColl; /* Collating sequence for LHS */
8151882079
sqlite3 *db = pParse->db; /* Database connection */
8151982080
@@ -81540,15 +82101,17 @@
8154082101
}
8154182102
if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
8154282103
(pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
8154382104
return 0;
8154482105
}
81545
- sqlite3DequoteExpr(pRight);
81546
- z = (char *)pRight->token.z;
82106
+ z = (const char*)pRight->token.z;
8154782107
cnt = 0;
8154882108
if( z ){
81549
- while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
82109
+ n = pRight->token.n;
82110
+ while( cnt<n && (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
82111
+ cnt++;
82112
+ }
8155082113
}
8155182114
if( cnt==0 || 255==(u8)z[cnt-1] ){
8155282115
return 0;
8155382116
}
8155482117
*pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
@@ -82045,11 +82608,10 @@
8204582608
pRight = pExpr->x.pList->a[0].pExpr;
8204682609
pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
8204782610
if( pStr1 ){
8204882611
sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
8204982612
pStr1->token.n = nPattern;
82050
- pStr1->flags = EP_Dequoted;
8205182613
}
8205282614
pStr2 = sqlite3ExprDup(db, pStr1, 0);
8205382615
if( !db->mallocFailed ){
8205482616
u8 c, *pC;
8205582617
/* assert( pStr2->token.dyn ); */
@@ -82358,12 +82920,251 @@
8235882920
}
8235982921
#else
8236082922
#define TRACE_IDX_INPUTS(A)
8236182923
#define TRACE_IDX_OUTPUTS(A)
8236282924
#endif
82925
+
82926
+/*
82927
+** Required because bestIndex() is called by bestOrClauseIndex()
82928
+*/
82929
+static void bestIndex(
82930
+ Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);
82931
+
82932
+/*
82933
+** This routine attempts to find an scanning strategy that can be used
82934
+** to optimize an 'OR' expression that is part of a WHERE clause.
82935
+**
82936
+** The table associated with FROM clause term pSrc may be either a
82937
+** regular B-Tree table or a virtual table.
82938
+*/
82939
+static void bestOrClauseIndex(
82940
+ Parse *pParse, /* The parsing context */
82941
+ WhereClause *pWC, /* The WHERE clause */
82942
+ struct SrcList_item *pSrc, /* The FROM clause term to search */
82943
+ Bitmask notReady, /* Mask of cursors that are not available */
82944
+ ExprList *pOrderBy, /* The ORDER BY clause */
82945
+ WhereCost *pCost /* Lowest cost query plan */
82946
+){
82947
+#ifndef SQLITE_OMIT_OR_OPTIMIZATION
82948
+ const int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
82949
+ const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur); /* Bitmask for pSrc */
82950
+ WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm]; /* End of pWC->a[] */
82951
+ WhereTerm *pTerm; /* A single term of the WHERE clause */
82952
+
82953
+ /* Search the WHERE clause terms for a usable WO_OR term. */
82954
+ for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
82955
+ if( pTerm->eOperator==WO_OR
82956
+ && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
82957
+ && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
82958
+ ){
82959
+ WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
82960
+ WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
82961
+ WhereTerm *pOrTerm;
82962
+ int flags = WHERE_MULTI_OR;
82963
+ double rTotal = 0;
82964
+ double nRow = 0;
82965
+
82966
+ for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
82967
+ WhereCost sTermCost;
82968
+ WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
82969
+ (pOrTerm - pOrWC->a), (pTerm - pWC->a)
82970
+ ));
82971
+ if( pOrTerm->eOperator==WO_AND ){
82972
+ WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
82973
+ bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
82974
+ }else if( pOrTerm->leftCursor==iCur ){
82975
+ WhereClause tempWC;
82976
+ tempWC.pParse = pWC->pParse;
82977
+ tempWC.pMaskSet = pWC->pMaskSet;
82978
+ tempWC.op = TK_AND;
82979
+ tempWC.a = pOrTerm;
82980
+ tempWC.nTerm = 1;
82981
+ bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
82982
+ }else{
82983
+ continue;
82984
+ }
82985
+ rTotal += sTermCost.rCost;
82986
+ nRow += sTermCost.nRow;
82987
+ if( rTotal>=pCost->rCost ) break;
82988
+ }
82989
+
82990
+ /* If there is an ORDER BY clause, increase the scan cost to account
82991
+ ** for the cost of the sort. */
82992
+ if( pOrderBy!=0 ){
82993
+ rTotal += nRow*estLog(nRow);
82994
+ WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
82995
+ }
82996
+
82997
+ /* If the cost of scanning using this OR term for optimization is
82998
+ ** less than the current cost stored in pCost, replace the contents
82999
+ ** of pCost. */
83000
+ WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
83001
+ if( rTotal<pCost->rCost ){
83002
+ pCost->rCost = rTotal;
83003
+ pCost->nRow = nRow;
83004
+ pCost->plan.wsFlags = flags;
83005
+ pCost->plan.u.pTerm = pTerm;
83006
+ }
83007
+ }
83008
+ }
83009
+#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
83010
+}
8236383011
8236483012
#ifndef SQLITE_OMIT_VIRTUALTABLE
83013
+/*
83014
+** Allocate and populate an sqlite3_index_info structure. It is the
83015
+** responsibility of the caller to eventually release the structure
83016
+** by passing the pointer returned by this function to sqlite3_free().
83017
+*/
83018
+static sqlite3_index_info *allocateIndexInfo(
83019
+ Parse *pParse,
83020
+ WhereClause *pWC,
83021
+ struct SrcList_item *pSrc,
83022
+ ExprList *pOrderBy
83023
+){
83024
+ int i, j;
83025
+ int nTerm;
83026
+ struct sqlite3_index_constraint *pIdxCons;
83027
+ struct sqlite3_index_orderby *pIdxOrderBy;
83028
+ struct sqlite3_index_constraint_usage *pUsage;
83029
+ WhereTerm *pTerm;
83030
+ int nOrderBy;
83031
+ sqlite3_index_info *pIdxInfo;
83032
+
83033
+ WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
83034
+
83035
+ /* Count the number of possible WHERE clause constraints referring
83036
+ ** to this virtual table */
83037
+ for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
83038
+ if( pTerm->leftCursor != pSrc->iCursor ) continue;
83039
+ assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
83040
+ testcase( pTerm->eOperator==WO_IN );
83041
+ testcase( pTerm->eOperator==WO_ISNULL );
83042
+ if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
83043
+ nTerm++;
83044
+ }
83045
+
83046
+ /* If the ORDER BY clause contains only columns in the current
83047
+ ** virtual table then allocate space for the aOrderBy part of
83048
+ ** the sqlite3_index_info structure.
83049
+ */
83050
+ nOrderBy = 0;
83051
+ if( pOrderBy ){
83052
+ for(i=0; i<pOrderBy->nExpr; i++){
83053
+ Expr *pExpr = pOrderBy->a[i].pExpr;
83054
+ if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
83055
+ }
83056
+ if( i==pOrderBy->nExpr ){
83057
+ nOrderBy = pOrderBy->nExpr;
83058
+ }
83059
+ }
83060
+
83061
+ /* Allocate the sqlite3_index_info structure
83062
+ */
83063
+ pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
83064
+ + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
83065
+ + sizeof(*pIdxOrderBy)*nOrderBy );
83066
+ if( pIdxInfo==0 ){
83067
+ sqlite3ErrorMsg(pParse, "out of memory");
83068
+ /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
83069
+ return 0;
83070
+ }
83071
+
83072
+ /* Initialize the structure. The sqlite3_index_info structure contains
83073
+ ** many fields that are declared "const" to prevent xBestIndex from
83074
+ ** changing them. We have to do some funky casting in order to
83075
+ ** initialize those fields.
83076
+ */
83077
+ pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
83078
+ pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
83079
+ pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
83080
+ *(int*)&pIdxInfo->nConstraint = nTerm;
83081
+ *(int*)&pIdxInfo->nOrderBy = nOrderBy;
83082
+ *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
83083
+ *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
83084
+ *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
83085
+ pUsage;
83086
+
83087
+ for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
83088
+ if( pTerm->leftCursor != pSrc->iCursor ) continue;
83089
+ assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
83090
+ testcase( pTerm->eOperator==WO_IN );
83091
+ testcase( pTerm->eOperator==WO_ISNULL );
83092
+ if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
83093
+ pIdxCons[j].iColumn = pTerm->u.leftColumn;
83094
+ pIdxCons[j].iTermOffset = i;
83095
+ pIdxCons[j].op = (u8)pTerm->eOperator;
83096
+ /* The direct assignment in the previous line is possible only because
83097
+ ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
83098
+ ** following asserts verify this fact. */
83099
+ assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
83100
+ assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
83101
+ assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
83102
+ assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
83103
+ assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
83104
+ assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
83105
+ assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
83106
+ j++;
83107
+ }
83108
+ for(i=0; i<nOrderBy; i++){
83109
+ Expr *pExpr = pOrderBy->a[i].pExpr;
83110
+ pIdxOrderBy[i].iColumn = pExpr->iColumn;
83111
+ pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
83112
+ }
83113
+
83114
+ return pIdxInfo;
83115
+}
83116
+
83117
+/*
83118
+** The table object reference passed as the second argument to this function
83119
+** must represent a virtual table. This function invokes the xBestIndex()
83120
+** method of the virtual table with the sqlite3_index_info pointer passed
83121
+** as the argument.
83122
+**
83123
+** If an error occurs, pParse is populated with an error message and a
83124
+** non-zero value is returned. Otherwise, 0 is returned and the output
83125
+** part of the sqlite3_index_info structure is left populated.
83126
+**
83127
+** Whether or not an error is returned, it is the responsibility of the
83128
+** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
83129
+** that this is required.
83130
+*/
83131
+static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
83132
+ sqlite3_vtab *pVtab = pTab->pVtab;
83133
+ int i;
83134
+ int rc;
83135
+
83136
+ (void)sqlite3SafetyOff(pParse->db);
83137
+ WHERETRACE(("xBestIndex for %s\n", pTab->zName));
83138
+ TRACE_IDX_INPUTS(p);
83139
+ rc = pVtab->pModule->xBestIndex(pVtab, p);
83140
+ TRACE_IDX_OUTPUTS(p);
83141
+ (void)sqlite3SafetyOn(pParse->db);
83142
+
83143
+ if( rc!=SQLITE_OK ){
83144
+ if( rc==SQLITE_NOMEM ){
83145
+ pParse->db->mallocFailed = 1;
83146
+ }else if( !pVtab->zErrMsg ){
83147
+ sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
83148
+ }else{
83149
+ sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
83150
+ }
83151
+ }
83152
+ sqlite3DbFree(pParse->db, pVtab->zErrMsg);
83153
+ pVtab->zErrMsg = 0;
83154
+
83155
+ for(i=0; i<p->nConstraint; i++){
83156
+ if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
83157
+ sqlite3ErrorMsg(pParse,
83158
+ "table %s: xBestIndex returned an invalid plan", pTab->zName);
83159
+ }
83160
+ }
83161
+
83162
+ return pParse->nErr;
83163
+}
83164
+
83165
+
8236583166
/*
8236683167
** Compute the best index for a virtual table.
8236783168
**
8236883169
** The best index is computed by the xBestIndex method of the virtual
8236983170
** table module. This routine is really just a wrapper that sets up
@@ -82376,118 +83177,43 @@
8237683177
** invocations. The sqlite3_index_info structure is also used when
8237783178
** code is generated to access the virtual table. The whereInfoDelete()
8237883179
** routine takes care of freeing the sqlite3_index_info structure after
8237983180
** everybody has finished with it.
8238083181
*/
82381
-static double bestVirtualIndex(
82382
- Parse *pParse, /* The parsing context */
82383
- WhereClause *pWC, /* The WHERE clause */
82384
- struct SrcList_item *pSrc, /* The FROM clause term to search */
82385
- Bitmask notReady, /* Mask of cursors that are not available */
82386
- ExprList *pOrderBy, /* The order by clause */
82387
- int orderByUsable, /* True if we can potential sort */
82388
- sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
83182
+static void bestVirtualIndex(
83183
+ Parse *pParse, /* The parsing context */
83184
+ WhereClause *pWC, /* The WHERE clause */
83185
+ struct SrcList_item *pSrc, /* The FROM clause term to search */
83186
+ Bitmask notReady, /* Mask of cursors that are not available */
83187
+ ExprList *pOrderBy, /* The order by clause */
83188
+ WhereCost *pCost, /* Lowest cost query plan */
83189
+ sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
8238983190
){
8239083191
Table *pTab = pSrc->pTab;
82391
- sqlite3_vtab *pVtab = pTab->pVtab;
8239283192
sqlite3_index_info *pIdxInfo;
8239383193
struct sqlite3_index_constraint *pIdxCons;
82394
- struct sqlite3_index_orderby *pIdxOrderBy;
8239583194
struct sqlite3_index_constraint_usage *pUsage;
8239683195
WhereTerm *pTerm;
8239783196
int i, j;
8239883197
int nOrderBy;
82399
- int rc;
83198
+
83199
+ /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
83200
+ ** malloc in allocateIndexInfo() fails and this function returns leaving
83201
+ ** wsFlags in an uninitialized state, the caller may behave unpredictably.
83202
+ */
83203
+ memset(pCost, 0, sizeof(*pCost));
83204
+ pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
8240083205
8240183206
/* If the sqlite3_index_info structure has not been previously
82402
- ** allocated and initialized for this virtual table, then allocate
82403
- ** and initialize it now
83207
+ ** allocated and initialized, then allocate and initialize it now.
8240483208
*/
8240583209
pIdxInfo = *ppIdxInfo;
8240683210
if( pIdxInfo==0 ){
82407
- int nTerm;
82408
- WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
82409
-
82410
- /* Count the number of possible WHERE clause constraints referring
82411
- ** to this virtual table */
82412
- for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
82413
- if( pTerm->leftCursor != pSrc->iCursor ) continue;
82414
- assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
82415
- testcase( pTerm->eOperator==WO_IN );
82416
- testcase( pTerm->eOperator==WO_ISNULL );
82417
- if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
82418
- nTerm++;
82419
- }
82420
-
82421
- /* If the ORDER BY clause contains only columns in the current
82422
- ** virtual table then allocate space for the aOrderBy part of
82423
- ** the sqlite3_index_info structure.
82424
- */
82425
- nOrderBy = 0;
82426
- if( pOrderBy ){
82427
- for(i=0; i<pOrderBy->nExpr; i++){
82428
- Expr *pExpr = pOrderBy->a[i].pExpr;
82429
- if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
82430
- }
82431
- if( i==pOrderBy->nExpr ){
82432
- nOrderBy = pOrderBy->nExpr;
82433
- }
82434
- }
82435
-
82436
- /* Allocate the sqlite3_index_info structure
82437
- */
82438
- pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
82439
- + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
82440
- + sizeof(*pIdxOrderBy)*nOrderBy );
82441
- if( pIdxInfo==0 ){
82442
- sqlite3ErrorMsg(pParse, "out of memory");
82443
- /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
82444
- return (double)0;
82445
- }
82446
- *ppIdxInfo = pIdxInfo;
82447
-
82448
- /* Initialize the structure. The sqlite3_index_info structure contains
82449
- ** many fields that are declared "const" to prevent xBestIndex from
82450
- ** changing them. We have to do some funky casting in order to
82451
- ** initialize those fields.
82452
- */
82453
- pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
82454
- pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
82455
- pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
82456
- *(int*)&pIdxInfo->nConstraint = nTerm;
82457
- *(int*)&pIdxInfo->nOrderBy = nOrderBy;
82458
- *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
82459
- *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
82460
- *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
82461
- pUsage;
82462
-
82463
- for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
82464
- if( pTerm->leftCursor != pSrc->iCursor ) continue;
82465
- assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
82466
- testcase( pTerm->eOperator==WO_IN );
82467
- testcase( pTerm->eOperator==WO_ISNULL );
82468
- if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
82469
- pIdxCons[j].iColumn = pTerm->u.leftColumn;
82470
- pIdxCons[j].iTermOffset = i;
82471
- pIdxCons[j].op = (u8)pTerm->eOperator;
82472
- /* The direct assignment in the previous line is possible only because
82473
- ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
82474
- ** following asserts verify this fact. */
82475
- assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
82476
- assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
82477
- assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
82478
- assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
82479
- assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
82480
- assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
82481
- assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
82482
- j++;
82483
- }
82484
- for(i=0; i<nOrderBy; i++){
82485
- Expr *pExpr = pOrderBy->a[i].pExpr;
82486
- pIdxOrderBy[i].iColumn = pExpr->iColumn;
82487
- pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
82488
- }
83211
+ *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
83212
+ }
83213
+ if( pIdxInfo==0 ){
83214
+ return;
8248983215
}
8249083216
8249183217
/* At this point, the sqlite3_index_info structure that pIdxInfo points
8249283218
** to will have been initialized, either during the current invocation or
8249383219
** during some prior invocation. Now we just have to customize the
@@ -82498,18 +83224,11 @@
8249883224
/* The module name must be defined. Also, by this point there must
8249983225
** be a pointer to an sqlite3_vtab structure. Otherwise
8250083226
** sqlite3ViewGetColumnNames() would have picked up the error.
8250183227
*/
8250283228
assert( pTab->azModuleArg && pTab->azModuleArg[0] );
82503
- assert( pVtab );
82504
-#if 0
82505
- if( pTab->pVtab==0 ){
82506
- sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
82507
- pTab->azModuleArg[0], pTab->zName);
82508
- return 0.0;
82509
- }
82510
-#endif
83229
+ assert( pTab->pVtab );
8251183230
8251283231
/* Set the aConstraint[].usable fields and initialize all
8251383232
** output variables to zero.
8251483233
**
8251583234
** aConstraint[].usable is true for constraints where the right-hand
@@ -82545,44 +83264,41 @@
8254583264
pIdxInfo->needToFreeIdxStr = 0;
8254683265
pIdxInfo->orderByConsumed = 0;
8254783266
/* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
8254883267
pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
8254983268
nOrderBy = pIdxInfo->nOrderBy;
82550
- if( pIdxInfo->nOrderBy && !orderByUsable ){
82551
- *(int*)&pIdxInfo->nOrderBy = 0;
82552
- }
82553
-
82554
- (void)sqlite3SafetyOff(pParse->db);
82555
- WHERETRACE(("xBestIndex for %s\n", pTab->zName));
82556
- TRACE_IDX_INPUTS(pIdxInfo);
82557
- rc = pVtab->pModule->xBestIndex(pVtab, pIdxInfo);
82558
- TRACE_IDX_OUTPUTS(pIdxInfo);
82559
- (void)sqlite3SafetyOn(pParse->db);
82560
-
82561
- if( rc!=SQLITE_OK ){
82562
- if( rc==SQLITE_NOMEM ){
82563
- pParse->db->mallocFailed = 1;
82564
- }else if( !pVtab->zErrMsg ){
82565
- sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
82566
- }else{
82567
- sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
82568
- }
82569
- }
82570
- sqlite3DbFree(pParse->db, pVtab->zErrMsg);
82571
- pVtab->zErrMsg = 0;
82572
-
82573
- for(i=0; i<pIdxInfo->nConstraint; i++){
82574
- if( !pIdxInfo->aConstraint[i].usable && pUsage[i].argvIndex>0 ){
82575
- sqlite3ErrorMsg(pParse,
82576
- "table %s: xBestIndex returned an invalid plan", pTab->zName);
82577
- /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
82578
- return (double)0;
82579
- }
82580
- }
82581
-
82582
- *(int*)&pIdxInfo->nOrderBy = nOrderBy;
82583
- return pIdxInfo->estimatedCost;
83269
+ if( !pOrderBy ){
83270
+ pIdxInfo->nOrderBy = 0;
83271
+ }
83272
+
83273
+ if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
83274
+ return;
83275
+ }
83276
+
83277
+ /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
83278
+ ** inital value of lowestCost in this loop. If it is, then the
83279
+ ** (cost<lowestCost) test below will never be true.
83280
+ **
83281
+ ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
83282
+ ** is defined.
83283
+ */
83284
+ if( (SQLITE_BIG_DBL/((double)2))<pIdxInfo->estimatedCost ){
83285
+ pCost->rCost = (SQLITE_BIG_DBL/((double)2));
83286
+ }else{
83287
+ pCost->rCost = pIdxInfo->estimatedCost;
83288
+ }
83289
+ pCost->plan.u.pVtabIdx = pIdxInfo;
83290
+ if( pIdxInfo && pIdxInfo->orderByConsumed ){
83291
+ pCost->plan.wsFlags |= WHERE_ORDERBY;
83292
+ }
83293
+ pCost->plan.nEq = 0;
83294
+ pIdxInfo->nOrderBy = nOrderBy;
83295
+
83296
+ /* Try to find a more efficient access pattern by using multiple indexes
83297
+ ** to optimize an OR expression within the WHERE clause.
83298
+ */
83299
+ bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
8258483300
}
8258583301
#endif /* SQLITE_OMIT_VIRTUALTABLE */
8258683302
8258783303
/*
8258883304
** Find the query plan for accessing a particular table. Write the
@@ -82610,11 +83326,11 @@
8261083326
** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
8261183327
** in the SELECT statement, then no indexes are considered. However, the
8261283328
** selected plan may still take advantage of the tables built-in rowid
8261383329
** index.
8261483330
*/
82615
-static void bestIndex(
83331
+static void bestBtreeIndex(
8261683332
Parse *pParse, /* The parsing context */
8261783333
WhereClause *pWC, /* The WHERE clause */
8261883334
struct SrcList_item *pSrc, /* The FROM clause term to search */
8261983335
Bitmask notReady, /* Mask of cursors that are not available */
8262083336
ExprList *pOrderBy, /* The ORDER BY clause */
@@ -82628,11 +83344,10 @@
8262883344
int nEq; /* Number of == or IN constraints */
8262983345
int eqTermMask; /* Mask of valid equality operators */
8263083346
double cost; /* Cost of using pProbe */
8263183347
double nRow; /* Estimated number of rows in result set */
8263283348
int i; /* Loop counter */
82633
- Bitmask maskSrc; /* Bitmask for the pSrc table */
8263483349
8263583350
WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName,notReady));
8263683351
pProbe = pSrc->pTab->pIndex;
8263783352
if( pSrc->notIndexed ){
8263883353
pProbe = 0;
@@ -82744,65 +83459,11 @@
8274483459
pCost->nRow = nRow;
8274583460
pCost->plan.wsFlags = wsFlags;
8274683461
}
8274783462
}
8274883463
82749
-#ifndef SQLITE_OMIT_OR_OPTIMIZATION
82750
- /* Search for an OR-clause that can be used to look up the table.
82751
- */
82752
- maskSrc = getMask(pWC->pMaskSet, iCur);
82753
- for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
82754
- WhereClause tempWC;
82755
- tempWC = *pWC;
82756
- if( pTerm->eOperator==WO_OR
82757
- && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
82758
- && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 ){
82759
- WhereClause *pOrWC = &pTerm->u.pOrInfo->wc;
82760
- WhereTerm *pOrTerm;
82761
- int j;
82762
- int sortable = 0;
82763
- double rTotal = 0;
82764
- nRow = 0;
82765
- for(j=0, pOrTerm=pOrWC->a; j<pOrWC->nTerm; j++, pOrTerm++){
82766
- WhereCost sTermCost;
82767
- WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", j,i));
82768
- if( pOrTerm->eOperator==WO_AND ){
82769
- WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
82770
- bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
82771
- }else if( pOrTerm->leftCursor==iCur ){
82772
- tempWC.a = pOrTerm;
82773
- tempWC.nTerm = 1;
82774
- bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
82775
- }else{
82776
- continue;
82777
- }
82778
- rTotal += sTermCost.rCost;
82779
- nRow += sTermCost.nRow;
82780
- if( rTotal>=pCost->rCost ) break;
82781
- }
82782
- if( pOrderBy!=0 ){
82783
- if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) && !rev ){
82784
- sortable = 1;
82785
- }else{
82786
- rTotal += nRow*estLog(nRow);
82787
- WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
82788
- }
82789
- }
82790
- WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n",
82791
- rTotal, nRow));
82792
- if( rTotal<pCost->rCost ){
82793
- pCost->rCost = rTotal;
82794
- pCost->nRow = nRow;
82795
- pCost->plan.wsFlags = WHERE_MULTI_OR;
82796
- pCost->plan.u.pTerm = pTerm;
82797
- if( sortable ){
82798
- pCost->plan.wsFlags = WHERE_ORDERBY|WHERE_MULTI_OR;
82799
- }
82800
- }
82801
- }
82802
- }
82803
-#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
83464
+ bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
8280483465
8280583466
/* If the pSrc table is the right table of a LEFT JOIN then we may not
8280683467
** use an index to satisfy IS NULL constraints on that table. This is
8280783468
** because columns might end up being NULL if the table does not match -
8280883469
** a circumstance which the index cannot help us discover. Ticket #2177.
@@ -82823,13 +83484,14 @@
8282383484
int inMultIsEst = 0; /* True if inMultiplier is an estimate */
8282483485
8282583486
WHERETRACE(("... index %s:\n", pProbe->zName));
8282683487
8282783488
/* Count the number of columns in the index that are satisfied
82828
- ** by x=EXPR constraints or x IN (...) constraints. For a term
82829
- ** of the form x=EXPR we only have to do a single binary search.
82830
- ** But for x IN (...) we have to do a number of binary searched
83489
+ ** by x=EXPR or x IS NULL constraints or x IN (...) constraints.
83490
+ ** For a term of the form x=EXPR or x IS NULL we only have to do
83491
+ ** a single binary search. But for x IN (...) we have to do a
83492
+ ** number of binary searched
8283183493
** equal to the number of entries on the RHS of the IN operator.
8283283494
** The inMultipler variable with try to estimate the number of
8283383495
** binary searches needed.
8283483496
*/
8283583497
wsFlags = 0;
@@ -82845,10 +83507,12 @@
8284583507
inMultiplier *= 25;
8284683508
inMultIsEst = 1;
8284783509
}else if( pExpr->x.pList ){
8284883510
inMultiplier *= pExpr->x.pList->nExpr + 1;
8284983511
}
83512
+ }else if( pTerm->eOperator & WO_ISNULL ){
83513
+ wsFlags |= WHERE_COLUMN_NULL;
8285083514
}
8285183515
}
8285283516
nRow = pProbe->aiRowEst[i] * inMultiplier;
8285383517
/* If inMultiplier is an estimate and that estimate results in an
8285483518
** nRow it that is more than half number of rows in the table,
@@ -82857,13 +83521,16 @@
8285783521
nRow = pProbe->aiRowEst[0]/2;
8285883522
inMultiplier = nRow/pProbe->aiRowEst[i];
8285983523
}
8286083524
cost = nRow + inMultiplier*estLog(pProbe->aiRowEst[0]);
8286183525
nEq = i;
82862
- if( pProbe->onError!=OE_None && (wsFlags & WHERE_COLUMN_IN)==0
82863
- && nEq==pProbe->nColumn ){
82864
- wsFlags |= WHERE_UNIQUE;
83526
+ if( pProbe->onError!=OE_None && nEq==pProbe->nColumn ){
83527
+ testcase( wsFlags & WHERE_COLUMN_IN );
83528
+ testcase( wsFlags & WHERE_COLUMN_NULL );
83529
+ if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
83530
+ wsFlags |= WHERE_UNIQUE;
83531
+ }
8286583532
}
8286683533
WHERETRACE(("...... nEq=%d inMult=%.9g nRow=%.9g cost=%.9g\n",
8286783534
nEq, inMultiplier, nRow, cost));
8286883535
8286983536
/* Look for range constraints. Assume that each range constraint
@@ -82890,12 +83557,13 @@
8289083557
}
8289183558
8289283559
/* Add the additional cost of sorting if that is a factor.
8289383560
*/
8289483561
if( pOrderBy ){
82895
- if( (wsFlags & WHERE_COLUMN_IN)==0 &&
82896
- isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
83562
+ if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
83563
+ && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
83564
+ ){
8289783565
if( wsFlags==0 ){
8289883566
wsFlags = WHERE_COLUMN_RANGE;
8289983567
}
8290083568
wsFlags |= WHERE_ORDERBY;
8290183569
if( rev ){
@@ -82952,10 +83620,35 @@
8295283620
(pCost->plan.wsFlags & WHERE_INDEXED)!=0 ?
8295383621
pCost->plan.u.pIdx->zName : "(none)", pCost->nRow,
8295483622
pCost->rCost, pCost->plan.wsFlags, pCost->plan.nEq));
8295583623
}
8295683624
83625
+/*
83626
+** Find the query plan for accessing table pSrc->pTab. Write the
83627
+** best query plan and its cost into the WhereCost object supplied
83628
+** as the last parameter. This function may calculate the cost of
83629
+** both real and virtual table scans.
83630
+*/
83631
+static void bestIndex(
83632
+ Parse *pParse, /* The parsing context */
83633
+ WhereClause *pWC, /* The WHERE clause */
83634
+ struct SrcList_item *pSrc, /* The FROM clause term to search */
83635
+ Bitmask notReady, /* Mask of cursors that are not available */
83636
+ ExprList *pOrderBy, /* The ORDER BY clause */
83637
+ WhereCost *pCost /* Lowest cost query plan */
83638
+){
83639
+ if( IsVirtual(pSrc->pTab) ){
83640
+ sqlite3_index_info *p = 0;
83641
+ bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
83642
+ if( p->needToFreeIdxStr ){
83643
+ sqlite3_free(p->idxStr);
83644
+ }
83645
+ sqlite3DbFree(pParse->db, p);
83646
+ }else{
83647
+ bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
83648
+ }
83649
+}
8295783650
8295883651
/*
8295983652
** Disable a term in the WHERE clause. Except, do not disable the term
8296083653
** if it controls a LEFT OUTER JOIN and it did not originate in the ON
8296183654
** or USING clause of that join.
@@ -83148,37 +83841,18 @@
8314883841
}
8314983842
}
8315083843
return regBase;
8315183844
}
8315283845
83153
-/*
83154
-** Return TRUE if the WhereClause pWC contains no terms that
83155
-** are not virtual and which have not been coded.
83156
-**
83157
-** To put it another way, return TRUE if no additional WHERE clauses
83158
-** tests are required in order to establish that the current row
83159
-** should go to output and return FALSE if there are some terms of
83160
-** the WHERE clause that need to be validated before outputing the row.
83161
-*/
83162
-static int whereRowReadyForOutput(WhereClause *pWC){
83163
- WhereTerm *pTerm;
83164
- int j;
83165
-
83166
- for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
83167
- if( (pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED))==0 ) return 0;
83168
- }
83169
- return 1;
83170
-}
83171
-
8317283846
/*
8317383847
** Generate code for the start of the iLevel-th loop in the WHERE clause
8317483848
** implementation described by pWInfo.
8317583849
*/
8317683850
static Bitmask codeOneLoopStart(
8317783851
WhereInfo *pWInfo, /* Complete information about the WHERE clause */
8317883852
int iLevel, /* Which level of pWInfo->a[] should be coded */
83179
- u8 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
83853
+ u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
8318083854
Bitmask notReady /* Which tables are currently available */
8318183855
){
8318283856
int j, k; /* Loop counters */
8318383857
int iCur; /* The VDBE cursor for the table */
8318483858
int addrNxt; /* Where to jump to continue with the next IN case */
@@ -83190,24 +83864,22 @@
8319083864
Parse *pParse; /* Parsing context */
8319183865
Vdbe *v; /* The prepared stmt under constructions */
8319283866
struct SrcList_item *pTabItem; /* FROM clause term being coded */
8319383867
int addrBrk; /* Jump here to break out of the loop */
8319483868
int addrCont; /* Jump here to continue with next cycle */
83195
- int regRowSet; /* Write rowids to this RowSet if non-negative */
83196
- int codeRowSetEarly; /* True if index fully constrains the search */
83197
-
83869
+ int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
83870
+ int iReleaseReg = 0; /* Temp register to free before returning */
8319883871
8319983872
pParse = pWInfo->pParse;
8320083873
v = pParse->pVdbe;
8320183874
pWC = pWInfo->pWC;
8320283875
pLevel = &pWInfo->a[iLevel];
8320383876
pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
8320483877
iCur = pTabItem->iCursor;
8320583878
bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
83206
- omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0;
83207
- regRowSet = pWInfo->regRowSet;
83208
- codeRowSetEarly = 0;
83879
+ omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
83880
+ && (wctrlFlags & WHERE_FORCE_TABLE)==0;
8320983881
8321083882
/* Create labels for the "break" and "continue" instructions
8321183883
** for the current loop. Jump to addrBrk to break out of a loop.
8321283884
** Jump to cont to go immediately to the next iteration of the
8321383885
** loop.
@@ -83242,24 +83914,20 @@
8324283914
pVtabIdx->aConstraintUsage;
8324383915
const struct sqlite3_index_constraint *aConstraint =
8324483916
pVtabIdx->aConstraint;
8324583917
8324683918
iReg = sqlite3GetTempRange(pParse, nConstraint+2);
83247
- pParse->disableColCache++;
8324883919
for(j=1; j<=nConstraint; j++){
8324983920
for(k=0; k<nConstraint; k++){
8325083921
if( aUsage[k].argvIndex==j ){
8325183922
int iTerm = aConstraint[k].iTermOffset;
83252
- assert( pParse->disableColCache );
8325383923
sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
8325483924
break;
8325583925
}
8325683926
}
8325783927
if( k==nConstraint ) break;
8325883928
}
83259
- assert( pParse->disableColCache );
83260
- pParse->disableColCache--;
8326183929
sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
8326283930
sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
8326383931
sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
8326483932
pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
8326583933
pVtabIdx->needToFreeIdxStr = 0;
@@ -83270,15 +83938,10 @@
8327083938
}
8327183939
}
8327283940
pLevel->op = OP_VNext;
8327383941
pLevel->p1 = iCur;
8327483942
pLevel->p2 = sqlite3VdbeCurrentAddr(v);
83275
- codeRowSetEarly = regRowSet>=0 ? whereRowReadyForOutput(pWC) : 0;
83276
- if( codeRowSetEarly ){
83277
- sqlite3VdbeAddOp2(v, OP_VRowid, iCur, iReg);
83278
- sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, iReg);
83279
- }
8328083943
sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
8328183944
}else
8328283945
#endif /* SQLITE_OMIT_VIRTUALTABLE */
8328383946
8328483947
if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
@@ -83285,26 +83948,21 @@
8328583948
/* Case 1: We can directly reference a single row using an
8328683949
** equality comparison against the ROWID field. Or
8328783950
** we reference multiple rows using a "rowid IN (...)"
8328883951
** construct.
8328983952
*/
83290
- int r1;
83291
- int rtmp = sqlite3GetTempReg(pParse);
83953
+ iReleaseReg = sqlite3GetTempReg(pParse);
8329283954
pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
8329383955
assert( pTerm!=0 );
8329483956
assert( pTerm->pExpr!=0 );
8329583957
assert( pTerm->leftCursor==iCur );
8329683958
assert( omitTable==0 );
83297
- r1 = codeEqualityTerm(pParse, pTerm, pLevel, rtmp);
83959
+ iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
8329883960
addrNxt = pLevel->addrNxt;
83299
- sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, addrNxt);
83300
- sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, r1);
83301
- codeRowSetEarly = (pWC->nTerm==1 && regRowSet>=0) ?1:0;
83302
- if( codeRowSetEarly ){
83303
- sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
83304
- }
83305
- sqlite3ReleaseTempReg(pParse, rtmp);
83961
+ sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
83962
+ sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
83963
+ sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
8330683964
VdbeComment((v, "pk"));
8330783965
pLevel->op = OP_Noop;
8330883966
}else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
8330983967
/* Case 2: We have an inequality comparison against the ROWID field.
8331083968
*/
@@ -83367,22 +84025,16 @@
8336784025
start = sqlite3VdbeCurrentAddr(v);
8336884026
pLevel->op = bRev ? OP_Prev : OP_Next;
8336984027
pLevel->p1 = iCur;
8337084028
pLevel->p2 = start;
8337184029
pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
83372
- codeRowSetEarly = regRowSet>=0 ? whereRowReadyForOutput(pWC) : 0;
83373
- if( codeRowSetEarly || testOp!=OP_Noop ){
83374
- int r1 = sqlite3GetTempReg(pParse);
83375
- sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
83376
- if( testOp!=OP_Noop ){
83377
- sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, r1);
83378
- sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
83379
- }
83380
- if( codeRowSetEarly ){
83381
- sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
83382
- }
83383
- sqlite3ReleaseTempReg(pParse, r1);
84030
+ if( testOp!=OP_Noop ){
84031
+ iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
84032
+ sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
84033
+ sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
84034
+ sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
84035
+ sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
8338484036
}
8338584037
}else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
8338684038
/* Case 3: A scan using an index.
8338784039
**
8338884040
** The WHERE clause may contain zero or more equality
@@ -83503,16 +84155,11 @@
8350384155
start_constraints = pRangeStart || nEq>0;
8350484156
8350584157
/* Seek the index cursor to the start of the range. */
8350684158
nConstraint = nEq;
8350784159
if( pRangeStart ){
83508
- int dcc = pParse->disableColCache;
83509
- if( pRangeEnd ){
83510
- pParse->disableColCache++;
83511
- }
8351284160
sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
83513
- pParse->disableColCache = dcc;
8351484161
sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
8351584162
nConstraint++;
8351684163
}else if( isMinQuery ){
8351784164
sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
8351884165
nConstraint++;
@@ -83534,10 +84181,11 @@
8353484181
/* Load the value for the inequality constraint at the end of the
8353584182
** range (if any).
8353684183
*/
8353784184
nConstraint = nEq;
8353884185
if( pRangeEnd ){
84186
+ sqlite3ExprCacheRemove(pParse, regBase+nEq);
8353984187
sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
8354084188
sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
8354184189
codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
8354284190
nConstraint++;
8354384191
}
@@ -83565,24 +84213,21 @@
8356584213
testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
8356684214
if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
8356784215
sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
8356884216
sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
8356984217
}
84218
+ sqlite3ReleaseTempReg(pParse, r1);
8357084219
8357184220
/* Seek the table cursor, if required */
8357284221
disableTerm(pLevel, pRangeStart);
8357384222
disableTerm(pLevel, pRangeEnd);
83574
- codeRowSetEarly = regRowSet>=0 ? whereRowReadyForOutput(pWC) : 0;
83575
- if( !omitTable || codeRowSetEarly ){
83576
- sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1);
83577
- if( codeRowSetEarly ){
83578
- sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
83579
- }else{
83580
- sqlite3VdbeAddOp2(v, OP_Seek, iCur, r1); /* Deferred seek */
83581
- }
83582
- }
83583
- sqlite3ReleaseTempReg(pParse, r1);
84223
+ if( !omitTable ){
84224
+ iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
84225
+ sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
84226
+ sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
84227
+ sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
84228
+ }
8358484229
8358584230
/* Record the instruction used to terminate the loop. Disable
8358684231
** WHERE clause terms made redundant by the index range scan.
8358784232
*/
8358884233
pLevel->op = bRev ? OP_Prev : OP_Next;
@@ -83601,70 +84246,110 @@
8360184246
** CREATE INDEX i3 ON t1(c);
8360284247
**
8360384248
** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
8360484249
**
8360584250
** In the example, there are three indexed terms connected by OR.
83606
- ** The top of the loop is constructed by creating a RowSet object
83607
- ** and populating it. Then looping over elements of the rowset.
83608
- **
83609
- ** Null 1
83610
- ** # fill RowSet 1 with entries where a=5 using i1
83611
- ** # fill Rowset 1 with entries where b=7 using i2
83612
- ** # fill Rowset 1 with entries where c=11 and d=13 i3 and t1
83613
- ** A: RowSetRead 1, B, 2
83614
- ** Seek i, 2
83615
- **
83616
- ** The bottom of the loop looks like this:
83617
- **
83618
- ** Goto 0, A
83619
- ** B:
83620
- */
83621
- int regOrRowset; /* Register holding the RowSet object */
83622
- int regNextRowid; /* Register holding next rowid */
84251
+ ** The top of the loop looks like this:
84252
+ **
84253
+ ** Null 1 # Zero the rowset in reg 1
84254
+ **
84255
+ ** Then, for each indexed term, the following. The arguments to
84256
+ ** RowSetTest are such that the rowid of the current row is inserted
84257
+ ** into the RowSet. If it is already present, control skips the
84258
+ ** Gosub opcode and jumps straight to the code generated by WhereEnd().
84259
+ **
84260
+ ** sqlite3WhereBegin(<term>)
84261
+ ** RowSetTest # Insert rowid into rowset
84262
+ ** Gosub 2 A
84263
+ ** sqlite3WhereEnd()
84264
+ **
84265
+ ** Following the above, code to terminate the loop. Label A, the target
84266
+ ** of the Gosub above, jumps to the instruction right after the Goto.
84267
+ **
84268
+ ** Null 1 # Zero the rowset in reg 1
84269
+ ** Goto B # The loop is finished.
84270
+ **
84271
+ ** A: <loop body> # Return data, whatever.
84272
+ **
84273
+ ** Return 2 # Jump back to the Gosub
84274
+ **
84275
+ ** B: <after the loop>
84276
+ **
84277
+ */
8362384278
WhereClause *pOrWc; /* The OR-clause broken out into subterms */
83624
- WhereTerm *pOrTerm; /* A single subterm within the OR-clause */
84279
+ WhereTerm *pFinal; /* Final subterm within the OR-clause. */
8362584280
SrcList oneTab; /* Shortened table list */
84281
+
84282
+ int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
84283
+ int regRowset; /* Register for RowSet object */
84284
+ int regRowid; /* Register holding rowid */
84285
+ int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
84286
+ int iRetInit; /* Address of regReturn init */
84287
+ int ii;
8362684288
8362784289
pTerm = pLevel->plan.u.pTerm;
8362884290
assert( pTerm!=0 );
8362984291
assert( pTerm->eOperator==WO_OR );
8363084292
assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
8363184293
pOrWc = &pTerm->u.pOrInfo->wc;
83632
- codeRowSetEarly = (regRowSet>=0 && pWC->nTerm==1) ?1:0;
83633
-
83634
- if( codeRowSetEarly ){
83635
- regOrRowset = regRowSet;
83636
- }else{
83637
- regOrRowset = sqlite3GetTempReg(pParse);
83638
- sqlite3VdbeAddOp2(v, OP_Null, 0, regOrRowset);
83639
- }
84294
+ pFinal = &pOrWc->a[pOrWc->nTerm-1];
84295
+
84296
+ /* Set up a SrcList containing just the table being scanned by this loop. */
8364084297
oneTab.nSrc = 1;
8364184298
oneTab.nAlloc = 1;
8364284299
oneTab.a[0] = *pTabItem;
83643
- for(j=0, pOrTerm=pOrWc->a; j<pOrWc->nTerm; j++, pOrTerm++){
83644
- WhereInfo *pSubWInfo;
83645
- if( pOrTerm->leftCursor!=iCur && pOrTerm->eOperator!=WO_AND ) continue;
83646
- pSubWInfo = sqlite3WhereBegin(pParse, &oneTab, pOrTerm->pExpr, 0,
83647
- WHERE_FILL_ROWSET | WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE,
83648
- regOrRowset);
83649
- if( pSubWInfo ){
83650
- sqlite3WhereEnd(pSubWInfo);
83651
- }
83652
- }
83653
- sqlite3VdbeResolveLabel(v, addrCont);
83654
- if( !codeRowSetEarly ){
83655
- regNextRowid = sqlite3GetTempReg(pParse);
83656
- addrCont =
83657
- sqlite3VdbeAddOp3(v, OP_RowSetRead, regOrRowset,addrBrk,regNextRowid);
83658
- sqlite3VdbeAddOp2(v, OP_Seek, iCur, regNextRowid);
83659
- sqlite3ReleaseTempReg(pParse, regNextRowid);
83660
- /* sqlite3ReleaseTempReg(pParse, regOrRowset); // Preserve the RowSet */
83661
- pLevel->op = OP_Goto;
83662
- pLevel->p2 = addrCont;
83663
- }else{
83664
- pLevel->op = OP_Noop;
83665
- }
84300
+
84301
+ /* Initialize the rowset register to contain NULL. An SQL NULL is
84302
+ ** equivalent to an empty rowset.
84303
+ **
84304
+ ** Also initialize regReturn to contain the address of the instruction
84305
+ ** immediately following the OP_Return at the bottom of the loop. This
84306
+ ** is required in a few obscure LEFT JOIN cases where control jumps
84307
+ ** over the top of the loop into the body of it. In this case the
84308
+ ** correct response for the end-of-loop code (the OP_Return) is to
84309
+ ** fall through to the next instruction, just as an OP_Next does if
84310
+ ** called on an uninitialized cursor.
84311
+ */
84312
+ if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
84313
+ regRowset = ++pParse->nMem;
84314
+ regRowid = ++pParse->nMem;
84315
+ sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
84316
+ }
84317
+ iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
84318
+
84319
+ for(ii=0; ii<pOrWc->nTerm; ii++){
84320
+ WhereTerm *pOrTerm = &pOrWc->a[ii];
84321
+ if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
84322
+ WhereInfo *pSubWInfo; /* Info for single OR-term scan */
84323
+
84324
+ /* Loop through table entries that match term pOrTerm. */
84325
+ pSubWInfo = sqlite3WhereBegin(pParse, &oneTab, pOrTerm->pExpr, 0,
84326
+ WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE | WHERE_FORCE_TABLE);
84327
+ if( pSubWInfo ){
84328
+ if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
84329
+ int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
84330
+ int r;
84331
+ r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
84332
+ regRowid, 0);
84333
+ sqlite3VdbeAddOp4(v, OP_RowSetTest, regRowset,
84334
+ sqlite3VdbeCurrentAddr(v)+2,
84335
+ r, SQLITE_INT_TO_PTR(iSet), P4_INT32);
84336
+ }
84337
+ sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
84338
+
84339
+ /* Finish the loop through table entries that match term pOrTerm. */
84340
+ sqlite3WhereEnd(pSubWInfo);
84341
+ }
84342
+ }
84343
+ }
84344
+ sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
84345
+ /* sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); */
84346
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
84347
+ sqlite3VdbeResolveLabel(v, iLoopBody);
84348
+
84349
+ pLevel->op = OP_Return;
84350
+ pLevel->p1 = regReturn;
8366684351
disableTerm(pLevel, pTerm);
8366784352
}else
8366884353
#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
8366984354
8367084355
{
@@ -83677,11 +84362,10 @@
8367784362
assert( omitTable==0 );
8367884363
pLevel->op = aStep[bRev];
8367984364
pLevel->p1 = iCur;
8368084365
pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
8368184366
pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
83682
- codeRowSetEarly = 0;
8368384367
}
8368484368
notReady &= ~getMask(pWC->pMaskSet, iCur);
8368584369
8368684370
/* Insert code to test every subexpression that can be completely
8368784371
** computed using the current set of tables.
@@ -83696,13 +84380,11 @@
8369684380
pE = pTerm->pExpr;
8369784381
assert( pE!=0 );
8369884382
if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
8369984383
continue;
8370084384
}
83701
- pParse->disableColCache += k;
8370284385
sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
83703
- pParse->disableColCache -= k;
8370484386
k = 1;
8370584387
pTerm->wtFlags |= TERM_CODED;
8370684388
}
8370784389
8370884390
/* For a LEFT OUTER JOIN, generate code that will record the fact that
@@ -83710,12 +84392,11 @@
8371084392
*/
8371184393
if( pLevel->iLeftJoin ){
8371284394
pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
8371384395
sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
8371484396
VdbeComment((v, "record LEFT JOIN hit"));
83715
- sqlite3ExprClearColumnCache(pParse, pLevel->iTabCur);
83716
- sqlite3ExprClearColumnCache(pParse, pLevel->iIdxCur);
84397
+ sqlite3ExprCacheClear(pParse);
8371784398
for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
8371884399
testcase( pTerm->wtFlags & TERM_VIRTUAL );
8371984400
testcase( pTerm->wtFlags & TERM_CODED );
8372084401
if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
8372184402
if( (pTerm->prereqAll & notReady)!=0 ) continue;
@@ -83722,28 +84403,11 @@
8372284403
assert( pTerm->pExpr );
8372384404
sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
8372484405
pTerm->wtFlags |= TERM_CODED;
8372584406
}
8372684407
}
83727
-
83728
- /*
83729
- ** If it was requested to store the results in a rowset and that has
83730
- ** not already been do, then do so now.
83731
- */
83732
- if( regRowSet>=0 && !codeRowSetEarly ){
83733
- int r1 = sqlite3GetTempReg(pParse);
83734
-#ifndef SQLITE_OMIT_VIRTUALTABLE
83735
- if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
83736
- sqlite3VdbeAddOp2(v, OP_VRowid, iCur, r1);
83737
- }else
83738
-#endif
83739
- {
83740
- sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
83741
- }
83742
- sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
83743
- sqlite3ReleaseTempReg(pParse, r1);
83744
- }
84408
+ sqlite3ReleaseTempReg(pParse, iReleaseReg);
8374584409
8374684410
return notReady;
8374784411
}
8374884412
8374984413
#if defined(SQLITE_TEST)
@@ -83766,11 +84430,11 @@
8376684430
if( pWInfo ){
8376784431
int i;
8376884432
for(i=0; i<pWInfo->nLevel; i++){
8376984433
sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
8377084434
if( pInfo ){
83771
- assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed );
84435
+ /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
8377284436
if( pInfo->needToFreeIdxStr ){
8377384437
sqlite3_free(pInfo->idxStr);
8377484438
}
8377584439
sqlite3DbFree(db, pInfo);
8377684440
}
@@ -83872,12 +84536,11 @@
8387284536
SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
8387384537
Parse *pParse, /* The parser context */
8387484538
SrcList *pTabList, /* A list of all tables to be scanned */
8387584539
Expr *pWhere, /* The WHERE clause */
8387684540
ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
83877
- u8 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
83878
- int regRowSet /* Register hold RowSet if WHERE_FILL_ROWSET is set */
84541
+ u16 wctrlFlags /* One of the WHERE_* flags defined in sqliteInt.h */
8387984542
){
8388084543
int i; /* Loop counter */
8388184544
int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
8388284545
WhereInfo *pWInfo; /* Will become the return value of this function */
8388384546
Vdbe *v = pParse->pVdbe; /* The virtual database engine */
@@ -83887,24 +84550,19 @@
8388784550
struct SrcList_item *pTabItem; /* A single entry from pTabList */
8388884551
WhereLevel *pLevel; /* A single level in the pWInfo list */
8388984552
int iFrom; /* First unused FROM clause element */
8389084553
int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */
8389184554
sqlite3 *db; /* Database connection */
83892
- ExprList *pOrderBy = 0;
8389384555
8389484556
/* The number of tables in the FROM clause is limited by the number of
8389584557
** bits in a Bitmask
8389684558
*/
8389784559
if( pTabList->nSrc>BMS ){
8389884560
sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
8389984561
return 0;
8390084562
}
8390184563
83902
- if( ppOrderBy ){
83903
- pOrderBy = *ppOrderBy;
83904
- }
83905
-
8390684564
/* Allocate and initialize the WhereInfo structure that will become the
8390784565
** return value. A single allocation is used to store the WhereInfo
8390884566
** struct, the contents of WhereInfo.a[], the WhereClause structure
8390984567
** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
8391084568
** field (type Bitmask) it must be aligned on an 8-byte boundary on
@@ -83922,11 +84580,10 @@
8392284580
}
8392384581
pWInfo->nLevel = pTabList->nSrc;
8392484582
pWInfo->pParse = pParse;
8392584583
pWInfo->pTabList = pTabList;
8392684584
pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
83927
- pWInfo->regRowSet = (wctrlFlags & WHERE_FILL_ROWSET) ? regRowSet : -1;
8392884585
pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
8392984586
pWInfo->wctrlFlags = wctrlFlags;
8393084587
pMaskSet = (WhereMaskSet*)&pWC[1];
8393184588
8393284589
/* Split the WHERE clause into separate subexpressions where each
@@ -84009,48 +84666,32 @@
8400984666
int once = 0; /* True when first table is seen */
8401084667
8401184668
memset(&bestPlan, 0, sizeof(bestPlan));
8401284669
bestPlan.rCost = SQLITE_BIG_DBL;
8401384670
for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
84014
- int doNotReorder; /* True if this table should not be reordered */
84015
- WhereCost sCost; /* Cost information from bestIndex() */
84671
+ int doNotReorder; /* True if this table should not be reordered */
84672
+ WhereCost sCost; /* Cost information from best[Virtual]Index() */
84673
+ ExprList *pOrderBy; /* ORDER BY clause for index to optimize */
8401684674
8401784675
doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
8401884676
if( once && doNotReorder ) break;
8401984677
m = getMask(pMaskSet, pTabItem->iCursor);
8402084678
if( (m & notReady)==0 ){
8402184679
if( j==iFrom ) iFrom++;
8402284680
continue;
8402384681
}
84682
+ pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
84683
+
8402484684
assert( pTabItem->pTab );
8402584685
#ifndef SQLITE_OMIT_VIRTUALTABLE
8402684686
if( IsVirtual(pTabItem->pTab) ){
84027
- sqlite3_index_info *pVtabIdx; /* Current virtual index */
84028
- sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
84029
- sCost.rCost = bestVirtualIndex(pParse, pWC, pTabItem, notReady,
84030
- ppOrderBy ? *ppOrderBy : 0, i==0,
84031
- ppIdxInfo);
84032
- sCost.plan.wsFlags = WHERE_VIRTUALTABLE;
84033
- sCost.plan.u.pVtabIdx = pVtabIdx = *ppIdxInfo;
84034
- if( pVtabIdx && pVtabIdx->orderByConsumed ){
84035
- sCost.plan.wsFlags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
84036
- }
84037
- sCost.plan.nEq = 0;
84038
- /* (double)2 In case of SQLITE_OMIT_FLOATING_POINT... */
84039
- if( (SQLITE_BIG_DBL/((double)2))<sCost.rCost ){
84040
- /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
84041
- ** inital value of lowestCost in this loop. If it is, then
84042
- ** the (cost<lowestCost) test below will never be true.
84043
- */
84044
- /* (double)2 In case of SQLITE_OMIT_FLOATING_POINT... */
84045
- sCost.rCost = (SQLITE_BIG_DBL/((double)2));
84046
- }
84687
+ sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
84688
+ bestVirtualIndex(pParse, pWC, pTabItem, notReady, pOrderBy, &sCost, pp);
8404784689
}else
8404884690
#endif
8404984691
{
84050
- bestIndex(pParse, pWC, pTabItem, notReady,
84051
- (i==0 && ppOrderBy) ? *ppOrderBy : 0, &sCost);
84692
+ bestBtreeIndex(pParse, pWC, pTabItem, notReady, pOrderBy, &sCost);
8405284693
}
8405384694
if( once==0 || sCost.rCost<bestPlan.rCost ){
8405484695
once = 1;
8405584696
bestPlan = sCost;
8405684697
bestJ = j;
@@ -84091,11 +84732,11 @@
8409184732
assert( bestPlan.plan.u.pIdx==pIdx );
8409284733
}
8409384734
}
8409484735
}
8409584736
WHERETRACE(("*** Optimizer Finished ***\n"));
84096
- if( db->mallocFailed ){
84737
+ if( pParse->nErr || db->mallocFailed ){
8409784738
goto whereBeginError;
8409884739
}
8409984740
8410084741
/* If the total query only selects a single row, then the ORDER BY
8410184742
** clause is irrelevant.
@@ -84274,11 +84915,11 @@
8427484915
SrcList *pTabList = pWInfo->pTabList;
8427584916
sqlite3 *db = pParse->db;
8427684917
8427784918
/* Generate loop termination code.
8427884919
*/
84279
- sqlite3ExprClearColumnCache(pParse, -1);
84920
+ sqlite3ExprCacheClear(pParse);
8428084921
for(i=pTabList->nSrc-1; i>=0; i--){
8428184922
pLevel = &pWInfo->a[i];
8428284923
sqlite3VdbeResolveLabel(v, pLevel->addrCont);
8428384924
if( pLevel->op!=OP_Noop ){
8428484925
sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
@@ -84301,11 +84942,15 @@
8430184942
addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
8430284943
sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
8430384944
if( pLevel->iIdxCur>=0 ){
8430484945
sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
8430584946
}
84306
- sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
84947
+ if( pLevel->op==OP_Return ){
84948
+ sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
84949
+ }else{
84950
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
84951
+ }
8430784952
sqlite3VdbeJumpHere(v, addr);
8430884953
}
8430984954
}
8431084955
8431184956
/* The "break" point is here, just past the end of the outer loop.
@@ -86511,10 +87156,12 @@
8651187156
break;
8651287157
case 36: /* column ::= columnid type carglist */
8651387158
{
8651487159
yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
8651587160
yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
87161
+ yygotominor.yy0.quoted = 0;
87162
+ yygotominor.yy0.dyn = 0;
8651687163
}
8651787164
break;
8651887165
case 37: /* columnid ::= nm */
8651987166
{
8652087167
sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
@@ -87661,11 +88308,11 @@
8766188308
**
8766288309
** This file contains C code that splits an SQL input string up into
8766388310
** individual tokens and sends those tokens one-by-one over to the
8766488311
** parser for analysis.
8766588312
**
87666
-** $Id: tokenize.c,v 1.155 2009/03/31 03:41:57 shane Exp $
88313
+** $Id: tokenize.c,v 1.156 2009/05/01 21:13:37 drh Exp $
8766788314
*/
8766888315
8766988316
/*
8767088317
** The charMap() macro maps alphabetic characters into their
8767188318
** lower-case ASCII equivalent. On ASCII machines, this is just
@@ -88327,14 +88974,16 @@
8832788974
assert( pParse->nVarExpr==0 );
8832888975
assert( pParse->nVarExprAlloc==0 );
8832988976
assert( pParse->apVarExpr==0 );
8833088977
enableLookaside = db->lookaside.bEnabled;
8833188978
if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
88979
+ pParse->sLastToken.quoted = 1;
8833288980
while( !db->mallocFailed && zSql[i]!=0 ){
8833388981
assert( i>=0 );
8833488982
pParse->sLastToken.z = (u8*)&zSql[i];
8833588983
assert( pParse->sLastToken.dyn==0 );
88984
+ assert( pParse->sLastToken.quoted );
8833688985
pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
8833788986
i += pParse->sLastToken.n;
8833888987
if( i>mxSqlLen ){
8833988988
pParse->rc = SQLITE_TOOBIG;
8834088989
break;
@@ -88454,11 +89103,11 @@
8845489103
** This file contains C code that implements the sqlite3_complete() API.
8845589104
** This code used to be part of the tokenizer.c source file. But by
8845689105
** separating it out, the code will be automatically omitted from
8845789106
** static links that do not use it.
8845889107
**
88459
-** $Id: complete.c,v 1.7 2008/06/13 18:24:27 drh Exp $
89108
+** $Id: complete.c,v 1.8 2009/04/28 04:46:42 drh Exp $
8846089109
*/
8846189110
#ifndef SQLITE_OMIT_COMPLETE
8846289111
8846389112
/*
8846489113
** This is defined in tokenize.c. We just have to import the definition.
@@ -88549,11 +89198,11 @@
8854989198
static const u8 trans[7][8] = {
8855089199
/* Token: */
8855189200
/* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
8855289201
/* 0 START: */ { 0, 0, 1, 2, 3, 1, 1, 1, },
8855389202
/* 1 NORMAL: */ { 0, 1, 1, 1, 1, 1, 1, 1, },
88554
- /* 2 EXPLAIN: */ { 0, 2, 1, 1, 3, 1, 1, 1, },
89203
+ /* 2 EXPLAIN: */ { 0, 2, 2, 1, 3, 1, 1, 1, },
8855589204
/* 3 CREATE: */ { 0, 3, 1, 1, 1, 3, 4, 1, },
8855689205
/* 4 TRIGGER: */ { 5, 4, 4, 4, 4, 4, 4, 4, },
8855789206
/* 5 SEMI: */ { 5, 5, 4, 4, 4, 4, 4, 6, },
8855889207
/* 6 END: */ { 0, 6, 4, 4, 4, 4, 4, 4, },
8855989208
};
@@ -88731,11 +89380,11 @@
8873189380
** Main file for the SQLite library. The routines in this file
8873289381
** implement the programmer interface to the library. Routines in
8873389382
** other files are for internal use by SQLite and should not be
8873489383
** accessed by users of the library.
8873589384
**
88736
-** $Id: main.c,v 1.536 2009/04/09 01:23:49 drh Exp $
89385
+** $Id: main.c,v 1.548 2009/05/06 19:03:14 drh Exp $
8873789386
*/
8873889387
8873989388
#ifdef SQLITE_ENABLE_FTS3
8874089389
/************** Include fts3.h in the middle of main.c ***********************/
8874189390
/************** Begin file fts3.h ********************************************/
@@ -88966,18 +89615,20 @@
8896689615
if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
8896789616
FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
8896889617
sqlite3GlobalConfig.inProgress = 1;
8896989618
memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
8897089619
sqlite3RegisterGlobalFunctions();
88971
- rc = sqlite3_os_init();
89620
+ rc = sqlite3PcacheInitialize();
8897289621
if( rc==SQLITE_OK ){
88973
- rc = sqlite3PcacheInitialize();
89622
+ rc = sqlite3_os_init();
89623
+ }
89624
+ if( rc==SQLITE_OK ){
8897489625
sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
8897589626
sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
89627
+ sqlite3GlobalConfig.isInit = 1;
8897689628
}
8897789629
sqlite3GlobalConfig.inProgress = 0;
88978
- sqlite3GlobalConfig.isInit = (rc==SQLITE_OK ? 1 : 0);
8897989630
}
8898089631
sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
8898189632
8898289633
/* Go back under the static mutex and clean up the recursive
8898389634
** mutex to prevent a resource leak.
@@ -89015,22 +89666,24 @@
8901589666
8901689667
/*
8901789668
** Undo the effects of sqlite3_initialize(). Must not be called while
8901889669
** there are outstanding database connections or memory allocations or
8901989670
** while any part of SQLite is otherwise in use in any thread. This
89020
-** routine is not threadsafe. Not by a long shot.
89671
+** routine is not threadsafe. But it is safe to invoke this routine
89672
+** on when SQLite is already shut down. If SQLite is already shut down
89673
+** when this routine is invoked, then this routine is a harmless no-op.
8902189674
*/
8902289675
SQLITE_API int sqlite3_shutdown(void){
89023
- sqlite3GlobalConfig.isMallocInit = 0;
89024
- sqlite3PcacheShutdown();
8902589676
if( sqlite3GlobalConfig.isInit ){
89677
+ sqlite3GlobalConfig.isMallocInit = 0;
89678
+ sqlite3PcacheShutdown();
8902689679
sqlite3_os_end();
89680
+ sqlite3_reset_auto_extension();
89681
+ sqlite3MallocEnd();
89682
+ sqlite3MutexEnd();
89683
+ sqlite3GlobalConfig.isInit = 0;
8902789684
}
89028
- sqlite3_reset_auto_extension();
89029
- sqlite3MallocEnd();
89030
- sqlite3MutexEnd();
89031
- sqlite3GlobalConfig.isInit = 0;
8903289685
return SQLITE_OK;
8903389686
}
8903489687
8903589688
/*
8903689689
** This API allows applications to modify the global configuration of
@@ -89538,41 +90191,45 @@
8953890191
/*
8953990192
** Return a static string that describes the kind of error specified in the
8954090193
** argument.
8954190194
*/
8954290195
SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
89543
- const char *z;
89544
- switch( rc & 0xff ){
89545
- case SQLITE_ROW:
89546
- case SQLITE_DONE:
89547
- case SQLITE_OK: z = "not an error"; break;
89548
- case SQLITE_ERROR: z = "SQL logic error or missing database"; break;
89549
- case SQLITE_PERM: z = "access permission denied"; break;
89550
- case SQLITE_ABORT: z = "callback requested query abort"; break;
89551
- case SQLITE_BUSY: z = "database is locked"; break;
89552
- case SQLITE_LOCKED: z = "database table is locked"; break;
89553
- case SQLITE_NOMEM: z = "out of memory"; break;
89554
- case SQLITE_READONLY: z = "attempt to write a readonly database"; break;
89555
- case SQLITE_INTERRUPT: z = "interrupted"; break;
89556
- case SQLITE_IOERR: z = "disk I/O error"; break;
89557
- case SQLITE_CORRUPT: z = "database disk image is malformed"; break;
89558
- case SQLITE_FULL: z = "database or disk is full"; break;
89559
- case SQLITE_CANTOPEN: z = "unable to open database file"; break;
89560
- case SQLITE_EMPTY: z = "table contains no data"; break;
89561
- case SQLITE_SCHEMA: z = "database schema has changed"; break;
89562
- case SQLITE_TOOBIG: z = "String or BLOB exceeded size limit"; break;
89563
- case SQLITE_CONSTRAINT: z = "constraint failed"; break;
89564
- case SQLITE_MISMATCH: z = "datatype mismatch"; break;
89565
- case SQLITE_MISUSE: z = "library routine called out of sequence";break;
89566
- case SQLITE_NOLFS: z = "large file support is disabled"; break;
89567
- case SQLITE_AUTH: z = "authorization denied"; break;
89568
- case SQLITE_FORMAT: z = "auxiliary database format error"; break;
89569
- case SQLITE_RANGE: z = "bind or column index out of range"; break;
89570
- case SQLITE_NOTADB: z = "file is encrypted or is not a database";break;
89571
- default: z = "unknown error"; break;
89572
- }
89573
- return z;
90196
+ static const char* const aMsg[] = {
90197
+ /* SQLITE_OK */ "not an error",
90198
+ /* SQLITE_ERROR */ "SQL logic error or missing database",
90199
+ /* SQLITE_INTERNAL */ 0,
90200
+ /* SQLITE_PERM */ "access permission denied",
90201
+ /* SQLITE_ABORT */ "callback requested query abort",
90202
+ /* SQLITE_BUSY */ "database is locked",
90203
+ /* SQLITE_LOCKED */ "database table is locked",
90204
+ /* SQLITE_NOMEM */ "out of memory",
90205
+ /* SQLITE_READONLY */ "attempt to write a readonly database",
90206
+ /* SQLITE_INTERRUPT */ "interrupted",
90207
+ /* SQLITE_IOERR */ "disk I/O error",
90208
+ /* SQLITE_CORRUPT */ "database disk image is malformed",
90209
+ /* SQLITE_NOTFOUND */ 0,
90210
+ /* SQLITE_FULL */ "database or disk is full",
90211
+ /* SQLITE_CANTOPEN */ "unable to open database file",
90212
+ /* SQLITE_PROTOCOL */ 0,
90213
+ /* SQLITE_EMPTY */ "table contains no data",
90214
+ /* SQLITE_SCHEMA */ "database schema has changed",
90215
+ /* SQLITE_TOOBIG */ "String or BLOB exceeded size limit",
90216
+ /* SQLITE_CONSTRAINT */ "constraint failed",
90217
+ /* SQLITE_MISMATCH */ "datatype mismatch",
90218
+ /* SQLITE_MISUSE */ "library routine called out of sequence",
90219
+ /* SQLITE_NOLFS */ "large file support is disabled",
90220
+ /* SQLITE_AUTH */ "authorization denied",
90221
+ /* SQLITE_FORMAT */ "auxiliary database format error",
90222
+ /* SQLITE_RANGE */ "bind or column index out of range",
90223
+ /* SQLITE_NOTADB */ "file is encrypted or is not a database",
90224
+ };
90225
+ rc &= 0xff;
90226
+ if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
90227
+ return aMsg[rc];
90228
+ }else{
90229
+ return "unknown error";
90230
+ }
8957490231
}
8957590232
8957690233
/*
8957790234
** This routine implements a busy callback that sleeps and tries
8957890235
** again until a timeout value is reached. The timeout value is
@@ -89726,11 +90383,11 @@
8972690383
if( zFunctionName==0 ||
8972790384
(xFunc && (xFinal || xStep)) ||
8972890385
(!xFunc && (xFinal && !xStep)) ||
8972990386
(!xFunc && (!xFinal && xStep)) ||
8973090387
(nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
89731
- (255<(nName = sqlite3Strlen(db, zFunctionName))) ){
90388
+ (255<(nName = sqlite3Strlen30( zFunctionName))) ){
8973290389
sqlite3Error(db, SQLITE_ERROR, "bad parameters");
8973390390
return SQLITE_ERROR;
8973490391
}
8973590392
8973690393
#ifndef SQLITE_OMIT_UTF16
@@ -89852,11 +90509,11 @@
8985290509
SQLITE_API int sqlite3_overload_function(
8985390510
sqlite3 *db,
8985490511
const char *zName,
8985590512
int nArg
8985690513
){
89857
- int nName = sqlite3Strlen(db, zName);
90514
+ int nName = sqlite3Strlen30(zName);
8985890515
int rc;
8985990516
sqlite3_mutex_enter(db->mutex);
8986090517
if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
8986190518
sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
8986290519
0, sqlite3InvalidFunction, 0, 0);
@@ -89960,10 +90617,43 @@
8996090617
db->xRollbackCallback = xCallback;
8996190618
db->pRollbackArg = pArg;
8996290619
sqlite3_mutex_leave(db->mutex);
8996390620
return pRet;
8996490621
}
90622
+
90623
+/*
90624
+** This function returns true if main-memory should be used instead of
90625
+** a temporary file for transient pager files and statement journals.
90626
+** The value returned depends on the value of db->temp_store (runtime
90627
+** parameter) and the compile time value of SQLITE_TEMP_STORE. The
90628
+** following table describes the relationship between these two values
90629
+** and this functions return value.
90630
+**
90631
+** SQLITE_TEMP_STORE db->temp_store Location of temporary database
90632
+** ----------------- -------------- ------------------------------
90633
+** 0 any file (return 0)
90634
+** 1 1 file (return 0)
90635
+** 1 2 memory (return 1)
90636
+** 1 0 file (return 0)
90637
+** 2 1 file (return 0)
90638
+** 2 2 memory (return 1)
90639
+** 2 0 memory (return 1)
90640
+** 3 any memory (return 1)
90641
+*/
90642
+SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
90643
+#if SQLITE_TEMP_STORE==1
90644
+ return ( db->temp_store==2 );
90645
+#endif
90646
+#if SQLITE_TEMP_STORE==2
90647
+ return ( db->temp_store!=1 );
90648
+#endif
90649
+#if SQLITE_TEMP_STORE==3
90650
+ return 1;
90651
+#else
90652
+ return 0;
90653
+#endif
90654
+}
8996590655
8996690656
/*
8996790657
** This routine is called to create a connection to a database BTree
8996890658
** driver. If zFilename is the name of a file, then that file is
8996990659
** opened and used. If zFilename is the magic name ":memory:" then
@@ -89971,24 +90661,12 @@
8997190661
** the connection is closed.) If zFilename is NULL then the database
8997290662
** is a "virtual" database for transient use only and is deleted as
8997390663
** soon as the connection is closed.
8997490664
**
8997590665
** A virtual database can be either a disk file (that is automatically
89976
-** deleted when the file is closed) or it an be held entirely in memory,
89977
-** depending on the values of the SQLITE_TEMP_STORE compile-time macro and the
89978
-** db->temp_store variable, according to the following chart:
89979
-**
89980
-** SQLITE_TEMP_STORE db->temp_store Location of temporary database
89981
-** ----------------- -------------- ------------------------------
89982
-** 0 any file
89983
-** 1 1 file
89984
-** 1 2 memory
89985
-** 1 0 file
89986
-** 2 1 file
89987
-** 2 2 memory
89988
-** 2 0 memory
89989
-** 3 any memory
90666
+** deleted when the file is closed) or it an be held entirely in memory.
90667
+** The sqlite3TempInMemory() function is used to determine which.
8999090668
*/
8999190669
SQLITE_PRIVATE int sqlite3BtreeFactory(
8999290670
const sqlite3 *db, /* Main database when opening aux otherwise 0 */
8999390671
const char *zFilename, /* Name of the file containing the BTree database */
8999490672
int omitJournal, /* if TRUE then do not journal this file */
@@ -90005,26 +90683,15 @@
9000590683
btFlags |= BTREE_OMIT_JOURNAL;
9000690684
}
9000790685
if( db->flags & SQLITE_NoReadlock ){
9000890686
btFlags |= BTREE_NO_READLOCK;
9000990687
}
90010
- if( zFilename==0 ){
90011
-#if SQLITE_TEMP_STORE==0
90012
- /* Do nothing */
90013
-#endif
9001490688
#ifndef SQLITE_OMIT_MEMORYDB
90015
-#if SQLITE_TEMP_STORE==1
90016
- if( db->temp_store==2 ) zFilename = ":memory:";
90017
-#endif
90018
-#if SQLITE_TEMP_STORE==2
90019
- if( db->temp_store!=1 ) zFilename = ":memory:";
90020
-#endif
90021
-#if SQLITE_TEMP_STORE==3
90689
+ if( zFilename==0 && sqlite3TempInMemory(db) ){
9002290690
zFilename = ":memory:";
90691
+ }
9002390692
#endif
90024
-#endif /* SQLITE_OMIT_MEMORYDB */
90025
- }
9002690693
9002790694
if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
9002890695
vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
9002990696
}
9003090697
rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
@@ -90156,23 +90823,25 @@
9015690823
9015790824
/* If SQLITE_UTF16 is specified as the encoding type, transform this
9015890825
** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
9015990826
** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
9016090827
*/
90161
- enc2 = enc & ~SQLITE_UTF16_ALIGNED;
90162
- if( enc2==SQLITE_UTF16 ){
90828
+ enc2 = enc;
90829
+ testcase( enc2==SQLITE_UTF16 );
90830
+ testcase( enc2==SQLITE_UTF16_ALIGNED );
90831
+ if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
9016390832
enc2 = SQLITE_UTF16NATIVE;
9016490833
}
90165
- if( (enc2&~3)!=0 ){
90834
+ if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
9016690835
return SQLITE_MISUSE;
9016790836
}
9016890837
9016990838
/* Check if this call is removing or replacing an existing collation
9017090839
** sequence. If so, and there are active VMs, return busy. If there
9017190840
** are no active VMs, invalidate any pre-compiled statements.
9017290841
*/
90173
- nName = sqlite3Strlen(db, zName);
90842
+ nName = sqlite3Strlen30(zName);
9017490843
pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 0);
9017590844
if( pColl && pColl->xCmp ){
9017690845
if( db->activeVdbeCnt ){
9017790846
sqlite3Error(db, SQLITE_BUSY,
9017890847
"unable to delete/modify collation sequence due to active statements");
@@ -90305,10 +90974,11 @@
9030590974
sqlite3 *db;
9030690975
int rc;
9030790976
CollSeq *pColl;
9030890977
int isThreadsafe;
9030990978
90979
+ *ppDb = 0;
9031090980
#ifndef SQLITE_OMIT_AUTOINIT
9031190981
rc = sqlite3_initialize();
9031290982
if( rc ) return rc;
9031390983
#endif
9031490984
@@ -90364,13 +91034,13 @@
9036491034
#endif
9036591035
#ifdef SQLITE_ENABLE_LOAD_EXTENSION
9036691036
| SQLITE_LoadExtension
9036791037
#endif
9036891038
;
90369
- sqlite3HashInit(&db->aCollSeq, 0);
91039
+ sqlite3HashInit(&db->aCollSeq);
9037091040
#ifndef SQLITE_OMIT_VIRTUALTABLE
90371
- sqlite3HashInit(&db->aModule, 0);
91041
+ sqlite3HashInit(&db->aModule);
9037291042
#endif
9037391043
9037491044
db->pVfs = sqlite3_vfs_find(zVfs);
9037591045
if( !db->pVfs ){
9037691046
rc = SQLITE_ERROR;
9037791047
--- 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.6.13. 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.
@@ -9,17 +9,17 @@
9 **
10 ** This file is all you need to compile SQLite. To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library. (If you do not have
13 ** the "sqlite3.h" header file at hand, you will find a copy in the first
14 ** 5503 lines past this header comment.) Additional code files may be
15 ** needed if you want a wrapper to interface SQLite with your choice of
16 ** programming language. The code for the "sqlite3" command-line shell
17 ** is also in a separate file. This file contains only code for the core
18 ** SQLite library.
19 **
20 ** This amalgamation was generated on 2009-04-13 09:47:15 UTC.
21 */
22 #define SQLITE_CORE 1
23 #define SQLITE_AMALGAMATION 1
24 #ifndef SQLITE_PRIVATE
25 # define SQLITE_PRIVATE static
@@ -39,11 +39,11 @@
39 ** May you share freely, never taking more than you give.
40 **
41 *************************************************************************
42 ** Internal interface definitions for SQLite.
43 **
44 ** @(#) $Id: sqliteInt.h,v 1.854 2009/04/08 13:51:51 drh Exp $
45 */
46 #ifndef _SQLITEINT_H_
47 #define _SQLITEINT_H_
48
49 /*
@@ -367,14 +367,14 @@
367 defined(SQLITE_POW2_MEMORY_SIZE)==0
368 # define SQLITE_SYSTEM_MALLOC 1
369 #endif
370
371 /*
372 ** If SQLITE_MALLOC_SOFT_LIMIT is defined, then try to keep the
373 ** sizes of memory allocations below this value where possible.
374 */
375 #if defined(SQLITE_POW2_MEMORY_SIZE) && !defined(SQLITE_MALLOC_SOFT_LIMIT)
376 # define SQLITE_MALLOC_SOFT_LIMIT 1024
377 #endif
378
379 /*
380 ** We need to define _XOPEN_SOURCE as follows in order to enable
@@ -441,10 +441,24 @@
441 # define TESTONLY(X) X
442 #else
443 # define TESTONLY(X)
444 #endif
445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
446 /*
447 ** The ALWAYS and NEVER macros surround boolean expressions which
448 ** are intended to always be true or false, respectively. Such
449 ** expressions could be omitted from the code completely. But they
450 ** are included in a few cases in order to enhance the resilience
@@ -482,24 +496,10 @@
482 #else
483 # define likely(X) !!(X)
484 # define unlikely(X) !!(X)
485 #endif
486
487 /*
488 ** Sometimes we need a small amount of code such as a variable initialization
489 ** to setup for a later assert() statement. We do not want this code to
490 ** appear when assert() is disabled. The following macro is therefore
491 ** used to contain that setup code. The "VVA" acronym stands for
492 ** "Verification, Validation, and Accreditation". In other words, the
493 ** code within VVA_ONLY() will only run during verification processes.
494 */
495 #ifndef NDEBUG
496 # define VVA_ONLY(X) X
497 #else
498 # define VVA_ONLY(X)
499 #endif
500
501 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
502 /************** Begin file sqlite3.h *****************************************/
503 /*
504 ** 2001 September 15
505 **
@@ -530,11 +530,11 @@
530 ** The name of this file under configuration management is "sqlite.h.in".
531 ** The makefile makes some minor changes to this file (such as inserting
532 ** the version number) and changes its name to "sqlite3.h" as
533 ** part of the build process.
534 **
535 ** @(#) $Id: sqlite.h.in,v 1.440 2009/04/06 15:55:04 drh Exp $
536 */
537 #ifndef _SQLITE3_H_
538 #define _SQLITE3_H_
539 #include <stdarg.h> /* Needed for the definition of va_list */
540
@@ -599,12 +599,12 @@
599 **
600 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
601 **
602 ** Requirements: [H10011] [H10014]
603 */
604 #define SQLITE_VERSION "3.6.13"
605 #define SQLITE_VERSION_NUMBER 3006013
606
607 /*
608 ** CAPI3REF: Run-Time Library Version Numbers {H10020} <S60100>
609 ** KEYWORDS: sqlite3_version
610 **
@@ -1291,10 +1291,15 @@
1291 ** the process, or if it is the first time sqlite3_initialize() is invoked
1292 ** following a call to sqlite3_shutdown(). Only an effective call
1293 ** of sqlite3_initialize() does any initialization. All other calls
1294 ** are harmless no-ops.
1295 **
 
 
 
 
 
1296 ** Among other things, sqlite3_initialize() shall invoke
1297 ** sqlite3_os_init(). Similarly, sqlite3_shutdown()
1298 ** shall invoke sqlite3_os_end().
1299 **
1300 ** The sqlite3_initialize() routine returns [SQLITE_OK] on success.
@@ -1717,19 +1722,23 @@
1717 ** on the [database connection] specified by the first parameter.
1718 ** Only changes that are directly specified by the [INSERT], [UPDATE],
1719 ** or [DELETE] statement are counted. Auxiliary changes caused by
1720 ** triggers are not counted. Use the [sqlite3_total_changes()] function
1721 ** to find the total number of changes including changes caused by triggers.
 
 
 
1722 **
1723 ** A "row change" is a change to a single row of a single table
1724 ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
1725 ** are changed as side effects of REPLACE constraint resolution,
1726 ** rollback, ABORT processing, DROP TABLE, or by any other
1727 ** mechanisms do not count as direct row changes.
1728 **
1729 ** A "trigger context" is a scope of execution that begins and
1730 ** ends with the script of a trigger. Most SQL statements are
 
1731 ** evaluated outside of any trigger. This is the "top level"
1732 ** trigger context. If a trigger fires from the top level, a
1733 ** new trigger context is entered for the duration of that one
1734 ** trigger. Subtriggers create subcontexts for their duration.
1735 **
@@ -1747,20 +1756,12 @@
1747 ** changes in the most recently completed INSERT, UPDATE, or DELETE
1748 ** statement within the body of the same trigger.
1749 ** However, the number returned does not include changes
1750 ** caused by subtriggers since those have their own context.
1751 **
1752 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
1753 ** by dropping and recreating the table. Doing so is much faster than going
1754 ** through and deleting individual elements from the table. Because of this
1755 ** optimization, the deletions in "DELETE FROM table" are not row changes and
1756 ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
1757 ** functions, regardless of the number of elements that were originally
1758 ** in the table. To get an accurate count of the number of rows deleted, use
1759 ** "DELETE FROM table WHERE 1" instead. Or recompile using the
1760 ** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
1761 ** optimization on all queries.
1762 **
1763 ** Requirements:
1764 ** [H12241] [H12243]
1765 **
1766 ** If a separate thread makes changes on the same database connection
@@ -1770,31 +1771,25 @@
1770 SQLITE_API int sqlite3_changes(sqlite3*);
1771
1772 /*
1773 ** CAPI3REF: Total Number Of Rows Modified {H12260} <S10600>
1774 **
1775 ** This function returns the number of row changes caused by INSERT,
1776 ** UPDATE or DELETE statements since the [database connection] was opened.
1777 ** The count includes all changes from all trigger contexts. However,
1778 ** the count does not include changes used to implement REPLACE constraints,
1779 ** do rollbacks or ABORT processing, or DROP table processing.
 
 
 
 
1780 ** The changes are counted as soon as the statement that makes them is
1781 ** completed (when the statement handle is passed to [sqlite3_reset()] or
1782 ** [sqlite3_finalize()]).
1783 **
1784 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
1785 ** by dropping and recreating the table. (This is much faster than going
1786 ** through and deleting individual elements from the table.) Because of this
1787 ** optimization, the deletions in "DELETE FROM table" are not row changes and
1788 ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
1789 ** functions, regardless of the number of elements that were originally
1790 ** in the table. To get an accurate count of the number of rows deleted, use
1791 ** "DELETE FROM table WHERE 1" instead. Or recompile using the
1792 ** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
1793 ** optimization on all queries.
1794 **
1795 ** See also the [sqlite3_changes()] interface.
1796 **
1797 ** Requirements:
1798 ** [H12261] [H12263]
1799 **
1800 ** If a separate thread makes changes on the same database connection
@@ -1824,12 +1819,20 @@
1824 ** An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
1825 ** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
1826 ** that is inside an explicit transaction, then the entire transaction
1827 ** will be rolled back automatically.
1828 **
1829 ** A call to sqlite3_interrupt() has no effect on SQL statements
1830 ** that are started after sqlite3_interrupt() returns.
 
 
 
 
 
 
 
 
1831 **
1832 ** Requirements:
1833 ** [H12271] [H12272]
1834 **
1835 ** If the database connection closes while [sqlite3_interrupt()]
@@ -1838,23 +1841,33 @@
1838 SQLITE_API void sqlite3_interrupt(sqlite3*);
1839
1840 /*
1841 ** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} <S70200>
1842 **
1843 ** These routines are useful for command-line input to determine if the
1844 ** currently entered text seems to form complete a SQL statement or
1845 ** if additional input is needed before sending the text into
1846 ** SQLite for parsing. These routines return true if the input string
1847 ** appears to be a complete SQL statement. A statement is judged to be
1848 ** complete if it ends with a semicolon token and is not a fragment of a
1849 ** CREATE TRIGGER statement. Semicolons that are embedded within
1850 ** string literals or quoted identifier names or comments are not
1851 ** independent tokens (they are part of the token in which they are
1852 ** embedded) and thus do not count as a statement terminator.
 
 
 
 
1853 **
1854 ** These routines do not parse the SQL statements thus
1855 ** will not detect syntactically incorrect SQL.
 
 
 
 
 
 
1856 **
1857 ** Requirements: [H10511] [H10512]
1858 **
1859 ** The input to [sqlite3_complete()] must be a zero-terminated
1860 ** UTF-8 string.
@@ -2279,25 +2292,30 @@
2279 **
2280 ** When the callback returns [SQLITE_OK], that means the operation
2281 ** requested is ok. When the callback returns [SQLITE_DENY], the
2282 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2283 ** authorizer will fail with an error message explaining that
2284 ** access is denied. If the authorizer code is [SQLITE_READ]
2285 ** and the callback returns [SQLITE_IGNORE] then the
2286 ** [prepared statement] statement is constructed to substitute
2287 ** a NULL value in place of the table column that would have
2288 ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
2289 ** return can be used to deny an untrusted user access to individual
2290 ** columns of a table.
2291 **
2292 ** The first parameter to the authorizer callback is a copy of the third
2293 ** parameter to the sqlite3_set_authorizer() interface. The second parameter
2294 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2295 ** the particular action to be authorized. The third through sixth parameters
2296 ** to the callback are zero-terminated strings that contain additional
2297 ** details about the action to be authorized.
2298 **
 
 
 
 
 
 
 
 
 
 
 
2299 ** An authorizer is used when [sqlite3_prepare | preparing]
2300 ** SQL statements from an untrusted source, to ensure that the SQL statements
2301 ** do not try to access data they are not allowed to see, or that they do not
2302 ** try to execute malicious statements that damage the database. For
2303 ** example, an application may allow a user to enter arbitrary
@@ -2327,11 +2345,13 @@
2327 ** schema change. Hence, the application should ensure that the
2328 ** correct authorizer callback remains in place during the [sqlite3_step()].
2329 **
2330 ** Note that the authorizer callback is invoked only during
2331 ** [sqlite3_prepare()] or its variants. Authorization is not
2332 ** performed during statement evaluation in [sqlite3_step()].
 
 
2333 **
2334 ** Requirements:
2335 ** [H12501] [H12502] [H12503] [H12504] [H12505] [H12506] [H12507] [H12510]
2336 ** [H12511] [H12512] [H12520] [H12521] [H12522]
2337 */
@@ -3983,16 +4003,18 @@
3983 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
3984 ** and a UTF-16 string for sqlite3_create_collation16(). In all cases
3985 ** the name is passed as the second function argument.
3986 **
3987 ** The third argument may be one of the constants [SQLITE_UTF8],
3988 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
3989 ** routine expects to be passed pointers to strings encoded using UTF-8,
3990 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. The
3991 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
 
 
3992 ** the routine expects pointers to 16-bit word aligned strings
3993 ** of UTF-16 in the native byte order of the host computer.
3994 **
3995 ** A pointer to the user supplied routine must be passed as the fifth
3996 ** argument. If it is NULL, this is the same as deleting the collation
3997 ** sequence (so that SQLite cannot call it anymore).
3998 ** Each time the application supplied function is invoked, it is passed
@@ -4012,10 +4034,12 @@
4012 ** destroyed and is passed a copy of the fourth parameter void* pointer
4013 ** of the sqlite3_create_collation_v2().
4014 ** Collations are destroyed when they are overridden by later calls to the
4015 ** collation creation functions or when the [database connection] is closed
4016 ** using [sqlite3_close()].
 
 
4017 **
4018 ** Requirements:
4019 ** [H16603] [H16604] [H16606] [H16609] [H16612] [H16615] [H16618] [H16621]
4020 ** [H16624] [H16627] [H16630]
4021 */
@@ -4566,19 +4590,24 @@
4566 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
4567 typedef struct sqlite3_module sqlite3_module;
4568
4569 /*
4570 ** CAPI3REF: Virtual Table Object {H18000} <S20400>
4571 ** KEYWORDS: sqlite3_module
4572 ** EXPERIMENTAL
4573 **
4574 ** A module is a class of virtual tables. Each module is defined
4575 ** by an instance of the following structure. This structure consists
4576 ** mostly of methods for the module.
4577 **
4578 ** This interface is experimental and is subject to change or
4579 ** removal in future releases of SQLite.
 
 
 
 
 
4580 */
4581 struct sqlite3_module {
4582 int iVersion;
4583 int (*xCreate)(sqlite3*, void *pAux,
4584 int argc, const char *const*argv,
@@ -4612,12 +4641,12 @@
4612 ** CAPI3REF: Virtual Table Indexing Information {H18100} <S20400>
4613 ** KEYWORDS: sqlite3_index_info
4614 ** EXPERIMENTAL
4615 **
4616 ** The sqlite3_index_info structure and its substructures is used to
4617 ** pass information into and receive the reply from the xBestIndex
4618 ** method of an sqlite3_module. The fields under **Inputs** are the
4619 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
4620 ** results into the **Outputs** fields.
4621 **
4622 ** The aConstraint[] array records WHERE clause constraints of the form:
4623 **
@@ -4636,31 +4665,30 @@
4636 ** form that refer to the particular virtual table being queried.
4637 **
4638 ** Information about the ORDER BY clause is stored in aOrderBy[].
4639 ** Each term of aOrderBy records a column of the ORDER BY clause.
4640 **
4641 ** The xBestIndex method must fill aConstraintUsage[] with information
4642 ** about what parameters to pass to xFilter. If argvIndex>0 then
4643 ** the right-hand side of the corresponding aConstraint[] is evaluated
4644 ** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit
4645 ** is true, then the constraint is assumed to be fully handled by the
4646 ** virtual table and is not checked again by SQLite.
4647 **
4648 ** The idxNum and idxPtr values are recorded and passed into xFilter.
4649 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
 
 
4650 **
4651 ** The orderByConsumed means that output from xFilter will occur in
4652 ** the correct order to satisfy the ORDER BY clause so that no separate
4653 ** sorting step is required.
4654 **
4655 ** The estimatedCost value is an estimate of the cost of doing the
4656 ** particular lookup. A full scan of a table with N entries should have
4657 ** a cost of N. A binary search of a table of N entries should have a
4658 ** cost of approximately log(N).
4659 **
4660 ** This interface is experimental and is subject to change or
4661 ** removal in future releases of SQLite.
4662 */
4663 struct sqlite3_index_info {
4664 /* Inputs */
4665 int nConstraint; /* Number of entries in aConstraint */
4666 struct sqlite3_index_constraint {
@@ -4694,64 +4722,69 @@
4694
4695 /*
4696 ** CAPI3REF: Register A Virtual Table Implementation {H18200} <S20400>
4697 ** EXPERIMENTAL
4698 **
4699 ** This routine is used to register a new module name with a
4700 ** [database connection]. Module names must be registered before
4701 ** creating new virtual tables on the module, or before using
4702 ** preexisting virtual tables of the module.
4703 **
4704 ** This interface is experimental and is subject to change or
4705 ** removal in future releases of SQLite.
 
 
 
 
 
 
 
 
4706 */
4707 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
4708 sqlite3 *db, /* SQLite connection to register module with */
4709 const char *zName, /* Name of the module */
4710 const sqlite3_module *, /* Methods for the module */
4711 void * /* Client data for xCreate/xConnect */
4712 );
4713
4714 /*
4715 ** CAPI3REF: Register A Virtual Table Implementation {H18210} <S20400>
4716 ** EXPERIMENTAL
4717 **
4718 ** This routine is identical to the [sqlite3_create_module()] method above,
4719 ** except that it allows a destructor function to be specified. It is
4720 ** even more experimental than the rest of the virtual tables API.
 
 
4721 */
4722 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
4723 sqlite3 *db, /* SQLite connection to register module with */
4724 const char *zName, /* Name of the module */
4725 const sqlite3_module *, /* Methods for the module */
4726 void *, /* Client data for xCreate/xConnect */
4727 void(*xDestroy)(void*) /* Module destructor function */
4728 );
4729
4730 /*
4731 ** CAPI3REF: Virtual Table Instance Object {H18010} <S20400>
4732 ** KEYWORDS: sqlite3_vtab
4733 ** EXPERIMENTAL
4734 **
4735 ** Every module implementation uses a subclass of the following structure
4736 ** to describe a particular instance of the module. Each subclass will
 
4737 ** be tailored to the specific needs of the module implementation.
4738 ** The purpose of this superclass is to define certain fields that are
4739 ** common to all module implementations.
4740 **
4741 ** Virtual tables methods can set an error message by assigning a
4742 ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
4743 ** take care that any prior string is freed by a call to [sqlite3_free()]
4744 ** prior to assigning a new string to zErrMsg. After the error message
4745 ** is delivered up to the client application, the string will be automatically
4746 ** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note
4747 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
4748 ** since virtual tables are commonly implemented in loadable extensions which
4749 ** do not have access to sqlite3MPrintf() or sqlite3Free().
4750 **
4751 ** This interface is experimental and is subject to change or
4752 ** removal in future releases of SQLite.
4753 */
4754 struct sqlite3_vtab {
4755 const sqlite3_module *pModule; /* The module for this virtual table */
4756 int nRef; /* Used internally */
4757 char *zErrMsg; /* Error message from sqlite3_mprintf() */
@@ -4758,24 +4791,25 @@
4758 /* Virtual table implementations will typically add additional fields */
4759 };
4760
4761 /*
4762 ** CAPI3REF: Virtual Table Cursor Object {H18020} <S20400>
4763 ** KEYWORDS: sqlite3_vtab_cursor
4764 ** EXPERIMENTAL
4765 **
4766 ** Every module implementation uses a subclass of the following structure
4767 ** to describe cursors that point into the virtual table and are used
 
4768 ** to loop through the virtual table. Cursors are created using the
4769 ** xOpen method of the module. Each module implementation will define
 
 
 
4770 ** the content of a cursor structure to suit its own needs.
4771 **
4772 ** This superclass exists in order to define fields of the cursor that
4773 ** are common to all implementations.
4774 **
4775 ** This interface is experimental and is subject to change or
4776 ** removal in future releases of SQLite.
4777 */
4778 struct sqlite3_vtab_cursor {
4779 sqlite3_vtab *pVtab; /* Virtual table of this cursor */
4780 /* Virtual table implementations will typically add additional fields */
4781 };
@@ -4782,37 +4816,33 @@
4782
4783 /*
4784 ** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} <S20400>
4785 ** EXPERIMENTAL
4786 **
4787 ** The xCreate and xConnect methods of a module use the following API
 
4788 ** to declare the format (the names and datatypes of the columns) of
4789 ** the virtual tables they implement.
4790 **
4791 ** This interface is experimental and is subject to change or
4792 ** removal in future releases of SQLite.
4793 */
4794 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
4795
4796 /*
4797 ** CAPI3REF: Overload A Function For A Virtual Table {H18300} <S20400>
4798 ** EXPERIMENTAL
4799 **
4800 ** Virtual tables can provide alternative implementations of functions
4801 ** using the xFindFunction method. But global versions of those functions
 
4802 ** must exist in order to be overloaded.
4803 **
4804 ** This API makes sure a global version of a function with a particular
4805 ** name and number of parameters exists. If no such function exists
4806 ** before this API is called, a new function is created. The implementation
4807 ** of the new function always causes an exception to be thrown. So
4808 ** the new function is not good for anything by itself. Its only
4809 ** purpose is to be a placeholder function that can be overloaded
4810 ** by virtual tables.
4811 **
4812 ** This API should be considered part of the virtual table interface,
4813 ** which is experimental and subject to change.
4814 */
4815 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
4816
4817 /*
4818 ** The interface to the virtual-table mechanism defined above (back up
@@ -6020,11 +6050,11 @@
6020 **
6021 *************************************************************************
6022 ** This is the header file for the generic hash-table implemenation
6023 ** used in SQLite.
6024 **
6025 ** $Id: hash.h,v 1.12 2008/10/10 17:41:29 drh Exp $
6026 */
6027 #ifndef _SQLITE_HASH_H_
6028 #define _SQLITE_HASH_H_
6029
6030 /* Forward declarations of structures. */
@@ -6033,17 +6063,29 @@
6033
6034 /* A complete hash table is an instance of the following structure.
6035 ** The internals of this structure are intended to be opaque -- client
6036 ** code should not attempt to access or modify the fields of this structure
6037 ** directly. Change this structure only by using the routines below.
6038 ** However, many of the "procedures" and "functions" for modifying and
6039 ** accessing this structure are really macros, so we can't really make
6040 ** this structure opaque.
 
 
 
 
 
 
 
 
 
 
 
 
 
6041 */
6042 struct Hash {
6043 unsigned int copyKey: 1; /* True if copy of key made on insert */
6044 unsigned int htsize : 31; /* Number of buckets in the hash table */
6045 unsigned int count; /* Number of entries in this table */
6046 HashElem *first; /* The first element of the array */
6047 struct _ht { /* the hash table */
6048 int count; /* Number of entries with this hash */
6049 HashElem *chain; /* Pointer to first entry with this hash */
@@ -6055,22 +6097,21 @@
6055 **
6056 ** Again, this structure is intended to be opaque, but it can't really
6057 ** be opaque because it is used by macros.
6058 */
6059 struct HashElem {
6060 HashElem *next, *prev; /* Next and previous elements in the table */
6061 void *data; /* Data associated with this element */
6062 void *pKey; int nKey; /* Key associated with this element */
6063 };
6064
6065 /*
6066 ** Access routines. To delete, insert a NULL pointer.
6067 */
6068 SQLITE_PRIVATE void sqlite3HashInit(Hash*, int copyKey);
6069 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
6070 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
6071 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash*, const void *pKey, int nKey);
6072 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6073
6074 /*
6075 ** Macros for looping over all elements of a hash table. The idiom is
6076 ** like this:
@@ -6084,17 +6125,17 @@
6084 ** }
6085 */
6086 #define sqliteHashFirst(H) ((H)->first)
6087 #define sqliteHashNext(E) ((E)->next)
6088 #define sqliteHashData(E) ((E)->data)
6089 #define sqliteHashKey(E) ((E)->pKey)
6090 #define sqliteHashKeysize(E) ((E)->nKey)
6091
6092 /*
6093 ** Number of entries in a hash table
6094 */
6095 #define sqliteHashCount(H) ((H)->count)
6096
6097 #endif /* _SQLITE_HASH_H_ */
6098
6099 /************** End of hash.h ************************************************/
6100 /************** Continuing where we left off in sqliteInt.h ******************/
@@ -6592,11 +6633,11 @@
6592 *************************************************************************
6593 ** This header file defines the interface that the sqlite B-Tree file
6594 ** subsystem. See comments in the source code for a detailed description
6595 ** of what each interface routine does.
6596 **
6597 ** @(#) $Id: btree.h,v 1.113 2009/04/10 12:55:17 danielk1977 Exp $
6598 */
6599 #ifndef _BTREE_H_
6600 #define _BTREE_H_
6601
6602 /* TODO: This definition is just included so other modules compile. It
@@ -6727,11 +6768,11 @@
6727 );
6728 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
6729 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
6730 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
6731 const void *pData, int nData,
6732 int nZero, int bias);
6733 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
6734 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
6735 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
6736 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
6737 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor*);
@@ -6973,110 +7014,110 @@
6973 #define OP_OpenWrite 10
6974 #define OP_NotNull 72 /* same as TK_NOTNULL */
6975 #define OP_If 11
6976 #define OP_ToInt 144 /* same as TK_TO_INT */
6977 #define OP_String8 94 /* same as TK_STRING */
6978 #define OP_VRowid 12
6979 #define OP_CollSeq 13
6980 #define OP_OpenRead 14
6981 #define OP_Expire 15
6982 #define OP_AutoCommit 16
6983 #define OP_Gt 75 /* same as TK_GT */
6984 #define OP_Pagecount 17
6985 #define OP_IntegrityCk 18
6986 #define OP_Sort 20
6987 #define OP_Copy 21
6988 #define OP_Trace 22
6989 #define OP_Function 23
6990 #define OP_IfNeg 24
6991 #define OP_And 67 /* same as TK_AND */
6992 #define OP_Subtract 85 /* same as TK_MINUS */
6993 #define OP_Noop 25
6994 #define OP_Return 26
6995 #define OP_Remainder 88 /* same as TK_REM */
6996 #define OP_NewRowid 27
6997 #define OP_Multiply 86 /* same as TK_STAR */
6998 #define OP_Variable 28
6999 #define OP_String 29
7000 #define OP_RealAffinity 30
7001 #define OP_VRename 31
7002 #define OP_ParseSchema 32
7003 #define OP_VOpen 33
7004 #define OP_Close 34
7005 #define OP_CreateIndex 35
7006 #define OP_IsUnique 36
7007 #define OP_NotFound 37
7008 #define OP_Int64 38
7009 #define OP_MustBeInt 39
7010 #define OP_Halt 40
7011 #define OP_Rowid 41
7012 #define OP_IdxLT 42
7013 #define OP_AddImm 43
7014 #define OP_Statement 44
7015 #define OP_RowData 45
7016 #define OP_MemMax 46
7017 #define OP_Or 66 /* same as TK_OR */
7018 #define OP_NotExists 47
7019 #define OP_Gosub 48
7020 #define OP_Divide 87 /* same as TK_SLASH */
7021 #define OP_Integer 49
7022 #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
7023 #define OP_Prev 50
7024 #define OP_RowSetRead 51
7025 #define OP_Concat 89 /* same as TK_CONCAT */
7026 #define OP_RowSetAdd 52
7027 #define OP_BitAnd 80 /* same as TK_BITAND */
7028 #define OP_VColumn 53
7029 #define OP_CreateTable 54
7030 #define OP_Last 55
7031 #define OP_SeekLe 56
7032 #define OP_IsNull 71 /* same as TK_ISNULL */
7033 #define OP_IncrVacuum 57
7034 #define OP_IdxRowid 58
7035 #define OP_ShiftRight 83 /* same as TK_RSHIFT */
7036 #define OP_ResetCount 59
7037 #define OP_ContextPush 60
7038 #define OP_Yield 61
7039 #define OP_DropTrigger 62
7040 #define OP_DropIndex 63
7041 #define OP_IdxGE 64
7042 #define OP_IdxDelete 65
7043 #define OP_Vacuum 68
7044 #define OP_IfNot 69
7045 #define OP_DropTable 70
7046 #define OP_SeekLt 79
7047 #define OP_MakeRecord 90
7048 #define OP_ToBlob 142 /* same as TK_TO_BLOB */
7049 #define OP_ResultRow 91
7050 #define OP_Delete 92
7051 #define OP_AggFinal 95
7052 #define OP_Compare 96
7053 #define OP_ShiftLeft 82 /* same as TK_LSHIFT */
7054 #define OP_Goto 97
7055 #define OP_TableLock 98
7056 #define OP_Clear 99
7057 #define OP_Le 76 /* same as TK_LE */
7058 #define OP_VerifyCookie 100
7059 #define OP_AggStep 101
7060 #define OP_ToText 141 /* same as TK_TO_TEXT */
7061 #define OP_Not 19 /* same as TK_NOT */
7062 #define OP_ToReal 145 /* same as TK_TO_REAL */
7063 #define OP_SetNumColumns 102
7064 #define OP_Transaction 103
7065 #define OP_VFilter 104
7066 #define OP_Ne 73 /* same as TK_NE */
7067 #define OP_VDestroy 105
7068 #define OP_ContextPop 106
7069 #define OP_BitOr 81 /* same as TK_BITOR */
7070 #define OP_Next 107
7071 #define OP_Count 108
7072 #define OP_IdxInsert 109
7073 #define OP_Lt 77 /* same as TK_LT */
7074 #define OP_SeekGe 110
7075 #define OP_Insert 111
7076 #define OP_Destroy 112
7077 #define OP_ReadCookie 113
 
7078 #define OP_LoadAnalysis 114
7079 #define OP_Explain 115
7080 #define OP_HaltIfNull 116
7081 #define OP_OpenPseudo 117
7082 #define OP_OpenEphemeral 118
@@ -7117,24 +7158,24 @@
7117 #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
7118 #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
7119 #define OPFLG_OUT3 0x0020 /* out3: P3 is an output */
7120 #define OPFLG_INITIALIZER {\
7121 /* 0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x08, 0x02, 0x00,\
7122 /* 8 */ 0x00, 0x04, 0x00, 0x05, 0x02, 0x00, 0x00, 0x00,\
7123 /* 16 */ 0x00, 0x02, 0x00, 0x04, 0x01, 0x04, 0x00, 0x00,\
7124 /* 24 */ 0x05, 0x00, 0x04, 0x02, 0x00, 0x02, 0x04, 0x00,\
7125 /* 32 */ 0x00, 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05,\
7126 /* 40 */ 0x00, 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11,\
7127 /* 48 */ 0x01, 0x02, 0x01, 0x21, 0x08, 0x00, 0x02, 0x01,\
7128 /* 56 */ 0x11, 0x01, 0x02, 0x00, 0x00, 0x04, 0x00, 0x00,\
7129 /* 64 */ 0x11, 0x00, 0x2c, 0x2c, 0x00, 0x05, 0x00, 0x05,\
7130 /* 72 */ 0x05, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x11,\
7131 /* 80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c,\
7132 /* 88 */ 0x2c, 0x2c, 0x00, 0x00, 0x00, 0x04, 0x02, 0x00,\
7133 /* 96 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7134 /* 104 */ 0x01, 0x00, 0x00, 0x01, 0x02, 0x08, 0x11, 0x00,\
7135 /* 112 */ 0x02, 0x02, 0x00, 0x00, 0x10, 0x00, 0x00, 0x02,\
7136 /* 120 */ 0x00, 0x02, 0x01, 0x11, 0x00, 0x00, 0x05, 0x00,\
7137 /* 128 */ 0x11, 0x05, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00,\
7138 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
7139 /* 144 */ 0x04, 0x04,}
7140
@@ -7216,11 +7257,11 @@
7216 *************************************************************************
7217 ** This header file defines the interface that the sqlite page cache
7218 ** subsystem. The page cache subsystem reads and writes a file a page
7219 ** at a time and provides a journal for rollback.
7220 **
7221 ** @(#) $Id: pager.h,v 1.100 2009/02/03 16:51:25 danielk1977 Exp $
7222 */
7223
7224 #ifndef _PAGER_H_
7225 #define _PAGER_H_
7226
@@ -7322,11 +7363,11 @@
7322 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
7323 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
7324
7325 /* Functions used to manage pager transactions and savepoints. */
7326 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
7327 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag);
7328 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
7329 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7330 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7331 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7332 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
@@ -7917,11 +7958,10 @@
7917 struct Schema {
7918 int schema_cookie; /* Database schema version number for this file */
7919 Hash tblHash; /* All tables indexed by name */
7920 Hash idxHash; /* All (named) indices indexed by name */
7921 Hash trigHash; /* All triggers indexed by name */
7922 Hash aFKey; /* Foreign keys indexed by to-table */
7923 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
7924 u8 file_format; /* Schema format version for this file */
7925 u8 enc; /* Text encoding used by this database */
7926 u16 flags; /* Flags associated with this schema */
7927 int cache_size; /* Number of pages to use in the cache */
@@ -8473,32 +8513,25 @@
8473 **
8474 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
8475 **
8476 ** Each REFERENCES clause generates an instance of the following structure
8477 ** which is attached to the from-table. The to-table need not exist when
8478 ** the from-table is created. The existence of the to-table is not checked
8479 ** until an attempt is made to insert data into the from-table.
8480 **
8481 ** The sqlite.aFKey hash table stores pointers to this structure
8482 ** given the name of a to-table. For each to-table, all foreign keys
8483 ** associated with that table are on a linked list using the FKey.pNextTo
8484 ** field.
8485 */
8486 struct FKey {
8487 Table *pFrom; /* The table that contains the REFERENCES clause */
8488 FKey *pNextFrom; /* Next foreign key in pFrom */
8489 char *zTo; /* Name of table that the key points to */
8490 FKey *pNextTo; /* Next foreign key that points to zTo */
8491 int nCol; /* Number of columns in this key */
8492 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
8493 int iFrom; /* Index of column in pFrom */
8494 char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
8495 } *aCol; /* One entry for each of nCol column s */
8496 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
8497 u8 updateConf; /* How to resolve conflicts that occur on UPDATE */
8498 u8 deleteConf; /* How to resolve conflicts that occur on DELETE */
8499 u8 insertConf; /* How to resolve conflicts that occur on INSERT */
 
 
 
 
8500 };
8501
8502 /*
8503 ** SQLite supports many different ways to resolve a constraint
8504 ** error. ROLLBACK processing means that a constraint violation
@@ -8568,10 +8601,11 @@
8568 */
8569 struct UnpackedRecord {
8570 KeyInfo *pKeyInfo; /* Collation and sort-order information */
8571 u16 nField; /* Number of entries in apMem[] */
8572 u16 flags; /* Boolean settings. UNPACKED_... below */
 
8573 Mem *aMem; /* Values */
8574 };
8575
8576 /*
8577 ** Allowed values of UnpackedRecord.flags
@@ -8579,10 +8613,11 @@
8579 #define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */
8580 #define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */
8581 #define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */
8582 #define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */
8583 #define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */
 
8584
8585 /*
8586 ** Each SQL index is represented in memory by an
8587 ** instance of the following structure.
8588 **
@@ -8632,12 +8667,13 @@
8632 ** may contain random values. Do not make any assumptions about Token.dyn
8633 ** and Token.n when Token.z==0.
8634 */
8635 struct Token {
8636 const unsigned char *z; /* Text of the token. Not NULL-terminated! */
8637 unsigned dyn : 1; /* True for malloced memory, false for static */
8638 unsigned n : 31; /* Number of characters in this token */
 
8639 };
8640
8641 /*
8642 ** An instance of this structure contains information needed to generate
8643 ** code for a SELECT that contains aggregate functions.
@@ -8795,11 +8831,11 @@
8795 #define EP_Agg 0x0002 /* Contains one or more aggregate functions */
8796 #define EP_Resolved 0x0004 /* IDs have been resolved to COLUMNs */
8797 #define EP_Error 0x0008 /* Expression contains one or more errors */
8798 #define EP_Distinct 0x0010 /* Aggregate function with DISTINCT keyword */
8799 #define EP_VarSelect 0x0020 /* pSelect is correlated, not constant */
8800 #define EP_Dequoted 0x0040 /* True if the string has been dequoted */
8801 #define EP_InfixFunc 0x0080 /* True for an infix function: LIKE, GLOB, etc */
8802 #define EP_ExpCollate 0x0100 /* Collating sequence specified explicitly */
8803 #define EP_AnyAff 0x0200 /* Can take a cached column of any affinity */
8804 #define EP_FixedDest 0x0400 /* Result needed in a specific register */
8805 #define EP_IntValue 0x0800 /* Integer value contained in iTable */
@@ -9020,19 +9056,21 @@
9020 */
9021 sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
9022 };
9023
9024 /*
9025 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin().
 
9026 */
9027 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
9028 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
9029 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
9030 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
9031 #define WHERE_FILL_ROWSET 0x0008 /* Save results in a RowSet object */
9032 #define WHERE_OMIT_OPEN 0x0010 /* Table cursor are already open */
9033 #define WHERE_OMIT_CLOSE 0x0020 /* Omit close of table & index cursors */
 
9034
9035 /*
9036 ** The WHERE clause processing routine has two halves. The
9037 ** first part does the start of the WHERE loop and the second
9038 ** half does the tail of the WHERE loop. An instance of
@@ -9041,11 +9079,10 @@
9041 */
9042 struct WhereInfo {
9043 Parse *pParse; /* Parsing and code generating context */
9044 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
9045 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE or DELETE */
9046 int regRowSet; /* Store rowids in this rowset if >=0 */
9047 SrcList *pTabList; /* List of tables in the join */
9048 int iTop; /* The very beginning of the WHERE loop */
9049 int iContinue; /* Jump here to continue with next record */
9050 int iBreak; /* Jump here to break out of the loop */
9051 int nLevel; /* Number of nested loop */
@@ -9169,10 +9206,17 @@
9169 int iParm; /* A parameter used by the eDest disposal method */
9170 int iMem; /* Base register where results are written */
9171 int nMem; /* Number of registers allocated */
9172 };
9173
 
 
 
 
 
 
 
9174 /*
9175 ** An SQL parser context. A copy of this structure is passed through
9176 ** the parser and down into all the parser action routine in order to
9177 ** carry around information that is global to the entire parse.
9178 **
@@ -9205,19 +9249,23 @@
9205 int nErr; /* Number of errors seen */
9206 int nTab; /* Number of previously allocated VDBE cursors */
9207 int nMem; /* Number of memory cells used so far */
9208 int nSet; /* Number of sets used so far */
9209 int ckBase; /* Base register of data during check constraints */
9210 int disableColCache; /* True to disable adding to column cache */
9211 int nColCache; /* Number of entries in the column cache */
9212 int iColCache; /* Next entry of the cache to replace */
 
9213 struct yColCache {
9214 int iTable; /* Table cursor number */
9215 int iColumn; /* Table column number */
9216 char affChange; /* True if this register has had an affinity change */
9217 int iReg; /* Register holding value of this column */
9218 } aColCache[10]; /* One for each valid column cache entry */
 
 
 
9219 u32 writeMask; /* Start a write transaction on these databases */
9220 u32 cookieMask; /* Bitmask of schema verified databases */
9221 int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
9222 int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
9223 #ifndef SQLITE_OMIT_SHARED_CACHE
@@ -9271,16 +9319,17 @@
9271 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
9272 Parse *pParse; /* The Parse structure */
9273 };
9274
9275 /*
9276 ** Bitfield flags for P2 value in OP_Insert and OP_Delete
9277 */
9278 #define OPFLAG_NCHANGE 1 /* Set to update db->nChange */
9279 #define OPFLAG_LASTROWID 2 /* Set to update db->lastRowid */
9280 #define OPFLAG_ISUPDATE 4 /* This OP_Insert is an sql UPDATE */
9281 #define OPFLAG_APPEND 8 /* This is likely to be an append */
 
9282
9283 /*
9284 * Each trigger present in the database schema is stored as an instance of
9285 * struct Trigger.
9286 *
@@ -9567,11 +9616,10 @@
9567 ** Internal function prototypes
9568 */
9569 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
9570 SQLITE_PRIVATE int sqlite3StrNICmp(const char *, const char *, int);
9571 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
9572 SQLITE_PRIVATE int sqlite3Strlen(sqlite3*, const char*);
9573 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
9574
9575 SQLITE_PRIVATE int sqlite3MallocInit(void);
9576 SQLITE_PRIVATE void sqlite3MallocEnd(void);
9577 SQLITE_PRIVATE void *sqlite3Malloc(int);
@@ -9626,12 +9674,11 @@
9626 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
9627 #endif
9628 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
9629 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
9630 SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
9631 SQLITE_PRIVATE void sqlite3Dequote(char*);
9632 SQLITE_PRIVATE void sqlite3DequoteExpr(Expr*);
9633 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
9634 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
9635 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
9636 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
9637 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
@@ -9675,10 +9722,11 @@
9675 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
9676
9677 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
9678 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
9679 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
 
9680 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
9681
9682 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
9683
9684 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
@@ -9716,18 +9764,21 @@
9716 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
9717 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
9718 #endif
9719 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
9720 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
9721 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u8, int);
9722 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
9723 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, int);
9724 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
9725 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
9726 SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse*, int);
 
 
 
 
9727 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
9728 SQLITE_PRIVATE void sqlite3ExprWritableRegister(Parse*,int);
9729 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
9730 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
9731 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
9732 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
9733 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
@@ -9765,12 +9816,12 @@
9765 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
9766 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
9767 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
9768 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
9769 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
9770 int*,int,int,int,int);
9771 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
9772 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
9773 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
9774 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
9775 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3*,Token*,const Token*);
9776 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
@@ -10027,10 +10078,12 @@
10027 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10028 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
10029 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10030 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10031 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
 
 
10032
10033
10034 /*
10035 ** Available fault injectors. Should be numbered beginning with 0.
10036 */
@@ -10449,11 +10502,11 @@
10449 **
10450 ** There is only one exported symbol in this file - the function
10451 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
10452 ** All other code has file scope.
10453 **
10454 ** $Id: date.c,v 1.105 2009/04/03 12:04:37 drh Exp $
10455 **
10456 ** SQLite processes all times and dates as Julian Day numbers. The
10457 ** dates and times are stored as the number of days since noon
10458 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
10459 ** calendar system.
@@ -10774,18 +10827,19 @@
10774 static int parseDateOrTime(
10775 sqlite3_context *context,
10776 const char *zDate,
10777 DateTime *p
10778 ){
 
10779 if( parseYyyyMmDd(zDate,p)==0 ){
10780 return 0;
10781 }else if( parseHhMmSs(zDate, p)==0 ){
10782 return 0;
10783 }else if( sqlite3StrICmp(zDate,"now")==0){
10784 setDateTimeToCurrent(context, p);
10785 return 0;
10786 }else if( sqlite3IsNumber(zDate, 0, SQLITE_UTF8) ){
10787 double r;
10788 getValue(zDate, &r);
10789 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
10790 p->validJD = 1;
10791 return 0;
@@ -10979,11 +11033,11 @@
10979 **
10980 ** Treat the current value of p->iJD as the number of
10981 ** seconds since 1970. Convert to a real julian day number.
10982 */
10983 if( strcmp(z, "unixepoch")==0 && p->validJD ){
10984 p->iJD = p->iJD/86400 + 21086676*(i64)10000000;
10985 clearYMD_HMS_TZ(p);
10986 rc = 0;
10987 }
10988 #ifndef SQLITE_OMIT_LOCALTIME
10989 else if( strcmp(z, "utc")==0 ){
@@ -14965,11 +15019,11 @@
14965 **
14966 *************************************************************************
14967 **
14968 ** Memory allocation functions used throughout sqlite.
14969 **
14970 ** $Id: malloc.c,v 1.61 2009/03/24 15:08:10 drh Exp $
14971 */
14972
14973 /*
14974 ** This routine runs when the memory allocator sees that the
14975 ** total memory allocation is about to exceed the soft heap
@@ -15602,11 +15656,11 @@
15602 char *zNew;
15603 size_t n;
15604 if( z==0 ){
15605 return 0;
15606 }
15607 n = (db ? sqlite3Strlen(db, z) : sqlite3Strlen30(z))+1;
15608 assert( (n&0x7fffffff)==n );
15609 zNew = sqlite3DbMallocRaw(db, (int)n);
15610 if( zNew ){
15611 memcpy(zNew, z, n);
15612 }
@@ -15677,11 +15731,11 @@
15677 ** the public domain. The original comments are included here for
15678 ** completeness. They are very out-of-date but might be useful as
15679 ** an historical reference. Most of the "enhancements" have been backed
15680 ** out so that the functionality is now the same as standard printf().
15681 **
15682 ** $Id: printf.c,v 1.102 2009/04/08 16:10:04 drh Exp $
15683 **
15684 **************************************************************************
15685 **
15686 ** The following modules is an enhanced replacement for the "printf" subroutines
15687 ** found in the standard C library. The following enhancements are
@@ -16062,13 +16116,17 @@
16062 /* Fall through into the next case */
16063 case etORDINAL:
16064 case etRADIX:
16065 if( infop->flags & FLAG_SIGNED ){
16066 i64 v;
16067 if( flag_longlong ) v = va_arg(ap,i64);
16068 else if( flag_long ) v = va_arg(ap,long int);
16069 else v = va_arg(ap,int);
 
 
 
 
16070 if( v<0 ){
16071 longvalue = -v;
16072 prefix = '-';
16073 }else{
16074 longvalue = v;
@@ -16075,13 +16133,17 @@
16075 if( flag_plussign ) prefix = '+';
16076 else if( flag_blanksign ) prefix = ' ';
16077 else prefix = 0;
16078 }
16079 }else{
16080 if( flag_longlong ) longvalue = va_arg(ap,u64);
16081 else if( flag_long ) longvalue = va_arg(ap,unsigned long int);
16082 else longvalue = va_arg(ap,unsigned int);
 
 
 
 
16083 prefix = 0;
16084 }
16085 if( longvalue==0 ) flag_alternateform = 0;
16086 if( flag_zeropad && precision<width-(prefix!=0) ){
16087 precision = width-(prefix!=0);
@@ -16824,11 +16886,11 @@
16824 ** VDBE. This information used to all be at the top of the single
16825 ** source code file "vdbe.c". When that file became too big (over
16826 ** 6000 lines long) it was split up into several smaller files and
16827 ** this header information was factored out.
16828 **
16829 ** $Id: vdbeInt.h,v 1.167 2009/04/10 12:55:17 danielk1977 Exp $
16830 */
16831 #ifndef _VDBEINT_H_
16832 #define _VDBEINT_H_
16833
16834 /*
@@ -16888,10 +16950,14 @@
16888 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
16889 int nField; /* Number of fields in the header */
16890 i64 seqCount; /* Sequence counter */
16891 sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
16892 const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
 
 
 
 
16893
16894 /* Cached information about the header for the data record that the
16895 ** cursor is currently pointing to. Only valid if cacheValid is true.
16896 ** aRow might point to (ephemeral) data for the current row, or it might
16897 ** be NULL.
@@ -17732,12 +17798,15 @@
17732 ** Utility functions used throughout sqlite.
17733 **
17734 ** This file contains functions for allocating memory, comparing
17735 ** strings, and stuff like that.
17736 **
17737 ** $Id: util.c,v 1.249 2009/03/01 22:29:20 drh Exp $
17738 */
 
 
 
17739
17740 /*
17741 ** Routine needed to support the testcase() macro.
17742 */
17743 #ifdef SQLITE_COVERAGE_TEST
@@ -17768,13 +17837,24 @@
17768 }
17769 #endif
17770
17771 /*
17772 ** Return true if the floating point value is Not a Number (NaN).
 
 
 
17773 */
17774 SQLITE_PRIVATE int sqlite3IsNaN(double x){
17775 /* This NaN test sometimes fails if compiled on GCC with -ffast-math.
 
 
 
 
 
 
 
 
17776 ** On the other hand, the use of -ffast-math comes with the following
17777 ** warning:
17778 **
17779 ** This option [-ffast-math] should never be turned on by any
17780 ** -O option since it can result in incorrect output for programs
@@ -17792,41 +17872,32 @@
17792 #ifdef __FAST_MATH__
17793 # error SQLite will not work correctly with the -ffast-math option of GCC.
17794 #endif
17795 volatile double y = x;
17796 volatile double z = y;
17797 return y!=z;
 
 
 
 
 
17798 }
17799
17800 /*
17801 ** Compute a string length that is limited to what can be stored in
17802 ** lower 30 bits of a 32-bit signed integer.
 
 
 
 
17803 */
17804 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
17805 const char *z2 = z;
17806 while( *z2 ){ z2++; }
17807 return 0x3fffffff & (int)(z2 - z);
17808 }
17809
17810 /*
17811 ** Return the length of a string, except do not allow the string length
17812 ** to exceed the SQLITE_LIMIT_LENGTH setting.
17813 */
17814 SQLITE_PRIVATE int sqlite3Strlen(sqlite3 *db, const char *z){
17815 const char *z2 = z;
17816 int len;
17817 int x;
17818 while( *z2 ){ z2++; }
17819 x = (int)(z2 - z);
17820 len = 0x7fffffff & x;
17821 if( len!=x || len > db->aLimit[SQLITE_LIMIT_LENGTH] ){
17822 return db->aLimit[SQLITE_LIMIT_LENGTH];
17823 }else{
17824 return len;
17825 }
17826 }
17827
17828 /*
17829 ** Set the most recent error code and error string for the sqlite
17830 ** handle "db". The error code is set to "err_code".
17831 **
17832 ** If it is not NULL, string zFormat specifies the format of the
@@ -17881,10 +17952,11 @@
17881 */
17882 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
17883 va_list ap;
17884 sqlite3 *db = pParse->db;
17885 pParse->nErr++;
 
17886 sqlite3DbFree(db, pParse->zErrMsg);
17887 va_start(ap, zFormat);
17888 pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap);
17889 va_end(ap);
17890 if( pParse->rc==SQLITE_OK ){
@@ -17904,40 +17976,48 @@
17904 /*
17905 ** Convert an SQL-style quoted string into a normal string by removing
17906 ** the quote characters. The conversion is done in-place. If the
17907 ** input does not begin with a quote character, then this routine
17908 ** is a no-op.
 
 
 
 
 
 
 
17909 **
17910 ** 2002-Feb-14: This routine is extended to remove MS-Access style
17911 ** brackets from around identifers. For example: "[a-b-c]" becomes
17912 ** "a-b-c".
17913 */
17914 SQLITE_PRIVATE void sqlite3Dequote(char *z){
17915 char quote;
17916 int i, j;
17917 if( z==0 ) return;
17918 quote = z[0];
17919 switch( quote ){
17920 case '\'': break;
17921 case '"': break;
17922 case '`': break; /* For MySQL compatibility */
17923 case '[': quote = ']'; break; /* For MS SqlServer compatibility */
17924 default: return;
17925 }
17926 for(i=1, j=0; z[i]; i++){
17927 if( z[i]==quote ){
17928 if( z[i+1]==quote ){
17929 z[j++] = quote;
17930 i++;
17931 }else{
17932 z[j++] = 0;
17933 break;
17934 }
17935 }else{
17936 z[j++] = z[i];
17937 }
17938 }
 
 
17939 }
17940
17941 /* Convenient short-hand */
17942 #define UpperToLower sqlite3UpperToLower
17943
@@ -17959,14 +18039,19 @@
17959 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
17960 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
17961 }
17962
17963 /*
17964 ** Return TRUE if z is a pure numeric string. Return FALSE if the
17965 ** string contains any character which is not part of a number. If
17966 ** the string is numeric and contains the '.' character, set *realnum
17967 ** to TRUE (otherwise FALSE).
 
 
 
 
 
17968 **
17969 ** An empty string is considered non-numeric.
17970 */
17971 SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
17972 int incr = (enc==SQLITE_UTF8?1:2);
@@ -17974,24 +18059,24 @@
17974 if( *z=='-' || *z=='+' ) z += incr;
17975 if( !sqlite3Isdigit(*z) ){
17976 return 0;
17977 }
17978 z += incr;
17979 if( realnum ) *realnum = 0;
17980 while( sqlite3Isdigit(*z) ){ z += incr; }
17981 if( *z=='.' ){
17982 z += incr;
17983 if( !sqlite3Isdigit(*z) ) return 0;
17984 while( sqlite3Isdigit(*z) ){ z += incr; }
17985 if( realnum ) *realnum = 1;
17986 }
17987 if( *z=='e' || *z=='E' ){
17988 z += incr;
17989 if( *z=='+' || *z=='-' ) z += incr;
17990 if( !sqlite3Isdigit(*z) ) return 0;
17991 while( sqlite3Isdigit(*z) ){ z += incr; }
17992 if( realnum ) *realnum = 1;
17993 }
17994 return *z==0;
17995 }
17996
17997 /*
@@ -18146,29 +18231,29 @@
18146 return compare2pow63(zNum)<neg;
18147 }
18148 }
18149
18150 /*
18151 ** The string zNum represents an integer. There might be some other
18152 ** information following the integer too, but that part is ignored.
18153 ** If the integer that the prefix of zNum represents will fit in a
18154 ** 64-bit signed integer, return TRUE. Otherwise return FALSE.
18155 **
18156 ** This routine returns FALSE for the string -9223372036854775808 even that
18157 ** that number will, in theory fit in a 64-bit integer. Positive
18158 ** 9223373036854775808 will not fit in 64 bits. So it seems safer to return
18159 ** false.
 
 
 
18160 */
18161 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
18162 int i, c;
18163 int neg = 0;
18164 if( *zNum=='-' ){
18165 neg = 1;
18166 zNum++;
18167 }else if( *zNum=='+' ){
18168 zNum++;
18169 }
18170 if( negFlag ) neg = 1-neg;
18171 while( *zNum=='0' ){
18172 zNum++; /* Skip leading zeros. Ticket #2454 */
18173 }
18174 for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
@@ -18469,50 +18554,84 @@
18469 ** this function assumes the single-byte case has already been handled.
18470 */
18471 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
18472 u32 a,b;
18473
 
 
18474 a = *p;
18475 /* a: p0 (unmasked) */
18476 #ifndef getVarint32
18477 if (!(a&0x80))
18478 {
 
18479 *v = a;
18480 return 1;
18481 }
18482 #endif
18483
 
18484 p++;
18485 b = *p;
18486 /* b: p1 (unmasked) */
18487 if (!(b&0x80))
18488 {
 
18489 a &= 0x7f;
18490 a = a<<7;
18491 *v = a | b;
18492 return 2;
18493 }
18494
 
18495 p++;
18496 a = a<<14;
18497 a |= *p;
18498 /* a: p0<<14 | p2 (unmasked) */
18499 if (!(a&0x80))
18500 {
 
18501 a &= (0x7f<<14)|(0x7f);
18502 b &= 0x7f;
18503 b = b<<7;
18504 *v = a | b;
18505 return 3;
18506 }
18507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18508 p++;
18509 b = b<<14;
18510 b |= *p;
18511 /* b: p1<<14 | p3 (unmasked) */
18512 if (!(b&0x80))
18513 {
 
18514 b &= (0x7f<<14)|(0x7f);
18515 a &= (0x7f<<14)|(0x7f);
18516 a = a<<7;
18517 *v = a | b;
18518 return 4;
@@ -18522,10 +18641,11 @@
18522 a = a<<14;
18523 a |= *p;
18524 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
18525 if (!(a&0x80))
18526 {
 
18527 a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
18528 b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
18529 b = b<<7;
18530 *v = a | b;
18531 return 5;
@@ -18543,10 +18663,11 @@
18543 n = sqlite3GetVarint(p, &v64);
18544 assert( n>5 && n<=9 );
18545 *v = (u32)v64;
18546 return n;
18547 }
 
18548 }
18549
18550 /*
18551 ** Return the number of bytes that will be needed to store the given
18552 ** 64-bit integer.
@@ -18554,11 +18675,11 @@
18554 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
18555 int i = 0;
18556 do{
18557 i++;
18558 v >>= 7;
18559 }while( v!=0 && i<9 );
18560 return i;
18561 }
18562
18563
18564 /*
@@ -18692,17 +18813,22 @@
18692 */
18693 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
18694 u32 magic;
18695 if( db==0 ) return 0;
18696 magic = db->magic;
18697 if( magic!=SQLITE_MAGIC_OPEN &&
18698 magic!=SQLITE_MAGIC_BUSY ) return 0;
18699 return 1;
 
 
 
 
 
 
18700 }
18701 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
18702 u32 magic;
18703 if( db==0 ) return 0;
18704 magic = db->magic;
18705 if( magic!=SQLITE_MAGIC_SICK &&
18706 magic!=SQLITE_MAGIC_OPEN &&
18707 magic!=SQLITE_MAGIC_BUSY ) return 0;
18708 return 1;
@@ -18722,23 +18848,20 @@
18722 **
18723 *************************************************************************
18724 ** This is the implementation of generic hash-tables
18725 ** used in SQLite.
18726 **
18727 ** $Id: hash.c,v 1.33 2009/01/09 01:12:28 drh Exp $
18728 */
18729
18730 /* Turn bulk memory into a hash table object by initializing the
18731 ** fields of the Hash structure.
18732 **
18733 ** "pNew" is a pointer to the hash table that is to be initialized.
18734 ** "copyKey" is true if the hash table should make its own private
18735 ** copy of keys and false if it should just use the supplied pointer.
18736 */
18737 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew, int copyKey){
18738 assert( pNew!=0 );
18739 pNew->copyKey = copyKey!=0;
18740 pNew->first = 0;
18741 pNew->count = 0;
18742 pNew->htsize = 0;
18743 pNew->ht = 0;
18744 }
@@ -18756,47 +18879,46 @@
18756 sqlite3_free(pH->ht);
18757 pH->ht = 0;
18758 pH->htsize = 0;
18759 while( elem ){
18760 HashElem *next_elem = elem->next;
18761 if( pH->copyKey ){
18762 sqlite3_free(elem->pKey);
18763 }
18764 sqlite3_free(elem);
18765 elem = next_elem;
18766 }
18767 pH->count = 0;
18768 }
18769
18770 /*
18771 ** Hash and comparison functions when the mode is SQLITE_HASH_STRING
18772 */
18773 static int strHash(const void *pKey, int nKey){
18774 const char *z = (const char *)pKey;
18775 int h = 0;
18776 if( nKey<=0 ) nKey = sqlite3Strlen30(z);
18777 while( nKey > 0 ){
18778 h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
18779 nKey--;
18780 }
18781 return h & 0x7fffffff;
18782 }
18783 static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
18784 if( n1!=n2 ) return 1;
18785 return sqlite3StrNICmp((const char*)pKey1,(const char*)pKey2,n1);
18786 }
18787
18788
18789 /* Link an element into the hash table
 
18790 */
18791 static void insertElement(
18792 Hash *pH, /* The complete hash table */
18793 struct _ht *pEntry, /* The entry into which pNew is inserted */
18794 HashElem *pNew /* The element to be inserted */
18795 ){
18796 HashElem *pHead; /* First element already in pEntry */
18797 pHead = pEntry->chain;
 
 
 
 
 
 
18798 if( pHead ){
18799 pNew->next = pHead;
18800 pNew->prev = pHead->prev;
18801 if( pHead->prev ){ pHead->prev->next = pNew; }
18802 else { pH->first = pNew; }
@@ -18805,73 +18927,77 @@
18805 pNew->next = pH->first;
18806 if( pH->first ){ pH->first->prev = pNew; }
18807 pNew->prev = 0;
18808 pH->first = pNew;
18809 }
18810 pEntry->count++;
18811 pEntry->chain = pNew;
18812 }
18813
18814
18815 /* Resize the hash table so that it cantains "new_size" buckets.
18816 ** "new_size" must be a power of 2. The hash table might fail
18817 ** to resize if sqlite3_malloc() fails.
 
 
18818 */
18819 static void rehash(Hash *pH, int new_size){
18820 struct _ht *new_ht; /* The new hash table */
18821 HashElem *elem, *next_elem; /* For looping over existing elements */
18822
18823 #ifdef SQLITE_MALLOC_SOFT_LIMIT
18824 if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
18825 new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
18826 }
18827 if( new_size==pH->htsize ) return;
18828 #endif
18829
18830 /* There is a call to sqlite3_malloc() inside rehash(). If there is
18831 ** already an allocation at pH->ht, then if this malloc() fails it
18832 ** is benign (since failing to resize a hash table is a performance
18833 ** hit only, not a fatal error).
18834 */
18835 if( pH->htsize>0 ) sqlite3BeginBenignMalloc();
18836 new_ht = (struct _ht *)sqlite3MallocZero( new_size*sizeof(struct _ht) );
18837 if( pH->htsize>0 ) sqlite3EndBenignMalloc();
18838
18839 if( new_ht==0 ) return;
18840 sqlite3_free(pH->ht);
18841 pH->ht = new_ht;
18842 pH->htsize = new_size;
 
18843 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
18844 int h = strHash(elem->pKey, elem->nKey) & (new_size-1);
18845 next_elem = elem->next;
18846 insertElement(pH, &new_ht[h], elem);
18847 }
 
18848 }
18849
18850 /* This function (for internal use only) locates an element in an
18851 ** hash table that matches the given key. The hash for this key has
18852 ** already been computed and is passed as the 4th parameter.
18853 */
18854 static HashElem *findElementGivenHash(
18855 const Hash *pH, /* The pH to be searched */
18856 const void *pKey, /* The key we are searching for */
18857 int nKey,
18858 int h /* The hash for this key. */
18859 ){
18860 HashElem *elem; /* Used to loop thru the element list */
18861 int count; /* Number of elements left to test */
18862
18863 if( pH->ht ){
18864 struct _ht *pEntry = &pH->ht[h];
18865 elem = pEntry->chain;
18866 count = pEntry->count;
18867 while( count-- && elem ){
18868 if( strCompare(elem->pKey,elem->nKey,pKey,nKey)==0 ){
18869 return elem;
18870 }
18871 elem = elem->next;
 
 
18872 }
 
18873 }
18874 return 0;
18875 }
18876
18877 /* Remove a single entry from the hash table given a pointer to that
@@ -18878,11 +19004,11 @@
18878 ** element and a hash on the element's key.
18879 */
18880 static void removeElementGivenHash(
18881 Hash *pH, /* The pH containing "elem" */
18882 HashElem* elem, /* The element to be removed from the pH */
18883 int h /* Hash value for the element */
18884 ){
18885 struct _ht *pEntry;
18886 if( elem->prev ){
18887 elem->prev->next = elem->next;
18888 }else{
@@ -18889,20 +19015,17 @@
18889 pH->first = elem->next;
18890 }
18891 if( elem->next ){
18892 elem->next->prev = elem->prev;
18893 }
18894 pEntry = &pH->ht[h];
18895 if( pEntry->chain==elem ){
18896 pEntry->chain = elem->next;
18897 }
18898 pEntry->count--;
18899 if( pEntry->count<=0 ){
18900 pEntry->chain = 0;
18901 }
18902 if( pH->copyKey ){
18903 sqlite3_free(elem->pKey);
18904 }
18905 sqlite3_free( elem );
18906 pH->count--;
18907 if( pH->count<=0 ){
18908 assert( pH->first==0 );
@@ -18909,108 +19032,86 @@
18909 assert( pH->count==0 );
18910 sqlite3HashClear(pH);
18911 }
18912 }
18913
18914 /* Attempt to locate an element of the hash table pH with a key
18915 ** that matches pKey,nKey. Return a pointer to the corresponding
18916 ** HashElem structure for this element if it is found, or NULL
18917 ** otherwise.
18918 */
18919 SQLITE_PRIVATE HashElem *sqlite3HashFindElem(const Hash *pH, const void *pKey, int nKey){
18920 int h; /* A hash on key */
18921 HashElem *elem; /* The element that matches key */
18922
18923 if( pH==0 || pH->ht==0 ) return 0;
18924 h = strHash(pKey,nKey);
18925 elem = findElementGivenHash(pH,pKey,nKey, h % pH->htsize);
18926 return elem;
18927 }
18928
18929 /* Attempt to locate an element of the hash table pH with a key
18930 ** that matches pKey,nKey. Return the data for this element if it is
18931 ** found, or NULL if there is no match.
18932 */
18933 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
18934 HashElem *elem; /* The element that matches key */
18935 elem = sqlite3HashFindElem(pH, pKey, nKey);
 
 
 
 
 
 
 
 
 
 
18936 return elem ? elem->data : 0;
18937 }
18938
18939 /* Insert an element into the hash table pH. The key is pKey,nKey
18940 ** and the data is "data".
18941 **
18942 ** If no element exists with a matching key, then a new
18943 ** element is created. A copy of the key is made if the copyKey
18944 ** flag is set. NULL is returned.
18945 **
18946 ** If another element already exists with the same key, then the
18947 ** new data replaces the old data and the old data is returned.
18948 ** The key is not copied in this instance. If a malloc fails, then
18949 ** the new data is returned and the hash table is unchanged.
18950 **
18951 ** If the "data" parameter to this function is NULL, then the
18952 ** element corresponding to "key" is removed from the hash table.
18953 */
18954 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
18955 int hraw; /* Raw hash value of the key */
18956 int h; /* the hash of the key modulo hash table size */
18957 HashElem *elem; /* Used to loop thru the element list */
18958 HashElem *new_elem; /* New element added to the pH */
18959
18960 assert( pH!=0 );
18961 hraw = strHash(pKey, nKey);
 
18962 if( pH->htsize ){
18963 h = hraw % pH->htsize;
18964 elem = findElementGivenHash(pH,pKey,nKey,h);
18965 if( elem ){
18966 void *old_data = elem->data;
18967 if( data==0 ){
18968 removeElementGivenHash(pH,elem,h);
18969 }else{
18970 elem->data = data;
18971 if( !pH->copyKey ){
18972 elem->pKey = (void *)pKey;
18973 }
18974 assert(nKey==elem->nKey);
18975 }
18976 return old_data;
18977 }
18978 }
18979 if( data==0 ) return 0;
18980 new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
18981 if( new_elem==0 ) return data;
18982 if( pH->copyKey && pKey!=0 ){
18983 new_elem->pKey = sqlite3Malloc( nKey );
18984 if( new_elem->pKey==0 ){
18985 sqlite3_free(new_elem);
18986 return data;
18987 }
18988 memcpy((void*)new_elem->pKey, pKey, nKey);
18989 }else{
18990 new_elem->pKey = (void*)pKey;
18991 }
18992 new_elem->nKey = nKey;
 
18993 pH->count++;
18994 if( pH->htsize==0 ){
18995 rehash(pH, 128/sizeof(pH->ht[0]));
18996 if( pH->htsize==0 ){
18997 pH->count = 0;
18998 if( pH->copyKey ){
18999 sqlite3_free(new_elem->pKey);
19000 }
19001 sqlite3_free(new_elem);
19002 return data;
19003 }
19004 }
19005 if( pH->count > pH->htsize ){
19006 rehash(pH,pH->htsize*2);
19007 }
19008 assert( pH->htsize>0 );
19009 h = hraw % pH->htsize;
19010 insertElement(pH, &pH->ht[h], new_elem);
19011 new_elem->data = data;
19012 return 0;
19013 }
19014
19015 /************** End of hash.c ************************************************/
19016 /************** Begin file opcodes.c *****************************************/
@@ -19028,78 +19129,78 @@
19028 /* 7 */ "Savepoint",
19029 /* 8 */ "RowKey",
19030 /* 9 */ "SCopy",
19031 /* 10 */ "OpenWrite",
19032 /* 11 */ "If",
19033 /* 12 */ "VRowid",
19034 /* 13 */ "CollSeq",
19035 /* 14 */ "OpenRead",
19036 /* 15 */ "Expire",
19037 /* 16 */ "AutoCommit",
19038 /* 17 */ "Pagecount",
19039 /* 18 */ "IntegrityCk",
19040 /* 19 */ "Not",
19041 /* 20 */ "Sort",
19042 /* 21 */ "Copy",
19043 /* 22 */ "Trace",
19044 /* 23 */ "Function",
19045 /* 24 */ "IfNeg",
19046 /* 25 */ "Noop",
19047 /* 26 */ "Return",
19048 /* 27 */ "NewRowid",
19049 /* 28 */ "Variable",
19050 /* 29 */ "String",
19051 /* 30 */ "RealAffinity",
19052 /* 31 */ "VRename",
19053 /* 32 */ "ParseSchema",
19054 /* 33 */ "VOpen",
19055 /* 34 */ "Close",
19056 /* 35 */ "CreateIndex",
19057 /* 36 */ "IsUnique",
19058 /* 37 */ "NotFound",
19059 /* 38 */ "Int64",
19060 /* 39 */ "MustBeInt",
19061 /* 40 */ "Halt",
19062 /* 41 */ "Rowid",
19063 /* 42 */ "IdxLT",
19064 /* 43 */ "AddImm",
19065 /* 44 */ "Statement",
19066 /* 45 */ "RowData",
19067 /* 46 */ "MemMax",
19068 /* 47 */ "NotExists",
19069 /* 48 */ "Gosub",
19070 /* 49 */ "Integer",
19071 /* 50 */ "Prev",
19072 /* 51 */ "RowSetRead",
19073 /* 52 */ "RowSetAdd",
19074 /* 53 */ "VColumn",
19075 /* 54 */ "CreateTable",
19076 /* 55 */ "Last",
19077 /* 56 */ "SeekLe",
19078 /* 57 */ "IncrVacuum",
19079 /* 58 */ "IdxRowid",
19080 /* 59 */ "ResetCount",
19081 /* 60 */ "ContextPush",
19082 /* 61 */ "Yield",
19083 /* 62 */ "DropTrigger",
19084 /* 63 */ "DropIndex",
19085 /* 64 */ "IdxGE",
19086 /* 65 */ "IdxDelete",
19087 /* 66 */ "Or",
19088 /* 67 */ "And",
19089 /* 68 */ "Vacuum",
19090 /* 69 */ "IfNot",
19091 /* 70 */ "DropTable",
19092 /* 71 */ "IsNull",
19093 /* 72 */ "NotNull",
19094 /* 73 */ "Ne",
19095 /* 74 */ "Eq",
19096 /* 75 */ "Gt",
19097 /* 76 */ "Le",
19098 /* 77 */ "Lt",
19099 /* 78 */ "Ge",
19100 /* 79 */ "SeekLt",
19101 /* 80 */ "BitAnd",
19102 /* 81 */ "BitOr",
19103 /* 82 */ "ShiftLeft",
19104 /* 83 */ "ShiftRight",
19105 /* 84 */ "Add",
@@ -19106,34 +19207,34 @@
19106 /* 85 */ "Subtract",
19107 /* 86 */ "Multiply",
19108 /* 87 */ "Divide",
19109 /* 88 */ "Remainder",
19110 /* 89 */ "Concat",
19111 /* 90 */ "MakeRecord",
19112 /* 91 */ "ResultRow",
19113 /* 92 */ "Delete",
19114 /* 93 */ "BitNot",
19115 /* 94 */ "String8",
19116 /* 95 */ "AggFinal",
19117 /* 96 */ "Compare",
19118 /* 97 */ "Goto",
19119 /* 98 */ "TableLock",
19120 /* 99 */ "Clear",
19121 /* 100 */ "VerifyCookie",
19122 /* 101 */ "AggStep",
19123 /* 102 */ "SetNumColumns",
19124 /* 103 */ "Transaction",
19125 /* 104 */ "VFilter",
19126 /* 105 */ "VDestroy",
19127 /* 106 */ "ContextPop",
19128 /* 107 */ "Next",
19129 /* 108 */ "Count",
19130 /* 109 */ "IdxInsert",
19131 /* 110 */ "SeekGe",
19132 /* 111 */ "Insert",
19133 /* 112 */ "Destroy",
19134 /* 113 */ "ReadCookie",
19135 /* 114 */ "LoadAnalysis",
19136 /* 115 */ "Explain",
19137 /* 116 */ "HaltIfNull",
19138 /* 117 */ "OpenPseudo",
19139 /* 118 */ "OpenEphemeral",
@@ -25901,11 +26002,11 @@
25901 **
25902 ******************************************************************************
25903 **
25904 ** This file contains code that is specific to windows.
25905 **
25906 ** $Id: os_win.c,v 1.154 2009/04/09 14:27:07 chw Exp $
25907 */
25908 #if SQLITE_OS_WIN /* This file is used for windows only */
25909
25910
25911 /*
@@ -27422,20 +27523,27 @@
27422 if( flags & SQLITE_OPEN_READWRITE ){
27423 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
27424 }else{
27425 dwDesiredAccess = GENERIC_READ;
27426 }
27427 if( flags & SQLITE_OPEN_CREATE ){
 
 
 
 
 
 
 
 
 
 
27428 dwCreationDisposition = OPEN_ALWAYS;
27429 }else{
 
27430 dwCreationDisposition = OPEN_EXISTING;
27431 }
27432 if( flags & SQLITE_OPEN_MAIN_DB ){
27433 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
27434 }else{
27435 dwShareMode = 0;
27436 }
27437 if( flags & SQLITE_OPEN_DELETEONCLOSE ){
27438 #if SQLITE_OS_WINCE
27439 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
27440 isTemp = 1;
27441 #else
@@ -27710,17 +27818,15 @@
27710 if( rc == SQLITE_OK )
27711 {
27712 void *zConverted = convertUtf8Filename(zFullpath);
27713 if( zConverted ){
27714 if( isNT() ){
27715 int i;
27716 /* trim path to just drive reference */
27717 WCHAR *p = zConverted;
27718 for(i=0;i<MAX_PATH;i++){
27719 if( p[i] == '\\' ){
27720 i++;
27721 p[i] = '\0';
27722 break;
27723 }
27724 }
27725 dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
27726 &dwDummy,
@@ -27727,17 +27833,15 @@
27727 &bytesPerSector,
27728 &dwDummy,
27729 &dwDummy);
27730 #if SQLITE_OS_WINCE==0
27731 }else{
27732 int i;
27733 /* trim path to just drive reference */
27734 CHAR *p = (CHAR *)zConverted;
27735 for(i=0;i<MAX_PATH;i++){
27736 if( p[i] == '\\' ){
27737 i++;
27738 p[i] = '\0';
27739 break;
27740 }
27741 }
27742 dwRet = GetDiskFreeSpaceA((CHAR*)zConverted,
27743 &dwDummy,
@@ -28987,11 +29091,11 @@
28987 ** sqlite3_pcache interface). It also contains part of the implementation
28988 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
28989 ** If the default page cache implementation is overriden, then neither of
28990 ** these two features are available.
28991 **
28992 ** @(#) $Id: pcache1.c,v 1.10 2009/03/23 04:33:33 danielk1977 Exp $
28993 */
28994
28995
28996 typedef struct PCache1 PCache1;
28997 typedef struct PgHdr1 PgHdr1;
@@ -29497,11 +29601,11 @@
29497 goto fetch_out;
29498 }
29499
29500 /* Step 4. Try to recycle a page buffer if appropriate. */
29501 if( pCache->bPurgeable && pcache1.pLruTail && (
29502 pCache->nPage>=pCache->nMax-1 || pcache1.nCurrentPage>=pcache1.nMaxPage
29503 )){
29504 pPage = pcache1.pLruTail;
29505 pcache1RemoveFromHash(pPage);
29506 pcache1PinPage(pPage);
29507 if( pPage->pCache->szPage!=pCache->szPage ){
@@ -29735,50 +29839,92 @@
29735 ** May you find forgiveness for yourself and forgive others.
29736 ** May you share freely, never taking more than you give.
29737 **
29738 *************************************************************************
29739 **
29740 ** This module implements an object we call a "Row Set".
29741 **
29742 ** The RowSet object is a bag of rowids. Rowids
29743 ** are inserted into the bag in an arbitrary order. Then they are
29744 ** pulled from the bag in sorted order. Rowids only appear in the
29745 ** bag once. If the same rowid is inserted multiple times, the
29746 ** second and subsequent inserts make no difference on the output.
29747 **
29748 ** This implementation accumulates rowids in a linked list. For
29749 ** output, it first sorts the linked list (removing duplicates during
29750 ** the sort) then returns elements one by one by walking the list.
29751 **
29752 ** Big chunks of rowid/next-ptr pairs are allocated at a time, to
29753 ** reduce the malloc overhead.
29754 **
29755 ** $Id: rowset.c,v 1.4 2009/04/01 19:35:55 drh Exp $
29756 */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29757
29758 /*
29759 ** The number of rowset entries per allocation chunk.
29760 */
29761 #define ROWSET_ENTRY_PER_CHUNK 63
 
29762
29763 /*
29764 ** Each entry in a RowSet is an instance of the following
29765 ** structure:
29766 */
29767 struct RowSetEntry {
29768 i64 v; /* ROWID value for this entry */
29769 struct RowSetEntry *pNext; /* Next entry on a list of all entries */
 
29770 };
29771
29772 /*
29773 ** Index entries are allocated in large chunks (instances of the
29774 ** following structure) to reduce memory allocation overhead. The
29775 ** chunks are kept on a linked list so that they can be deallocated
29776 ** when the RowSet is destroyed.
29777 */
29778 struct RowSetChunk {
29779 struct RowSetChunk *pNext; /* Next chunk on list of them all */
29780 struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
29781 };
29782
29783 /*
29784 ** A RowSet in an instance of the following structure.
@@ -29786,15 +29932,17 @@
29786 ** A typedef of this structure if found in sqliteInt.h.
29787 */
29788 struct RowSet {
29789 struct RowSetChunk *pChunk; /* List of all chunk allocations */
29790 sqlite3 *db; /* The database connection */
29791 struct RowSetEntry *pEntry; /* List of entries in the rowset */
29792 struct RowSetEntry *pLast; /* Last entry on the pEntry list */
29793 struct RowSetEntry *pFresh; /* Source of new entry objects */
 
29794 u16 nFresh; /* Number of objects on pFresh */
29795 u8 isSorted; /* True if content is sorted */
 
29796 };
29797
29798 /*
29799 ** Turn bulk memory into a RowSet object. N bytes of memory
29800 ** are available at pSpace. The db pointer is used as a memory context
@@ -29813,29 +29961,34 @@
29813 p = pSpace;
29814 p->pChunk = 0;
29815 p->db = db;
29816 p->pEntry = 0;
29817 p->pLast = 0;
 
29818 p->pFresh = (struct RowSetEntry*)&p[1];
29819 p->nFresh = (u16)((N - sizeof(*p))/sizeof(struct RowSetEntry));
29820 p->isSorted = 1;
 
29821 return p;
29822 }
29823
29824 /*
29825 ** Deallocate all chunks from a RowSet.
 
 
29826 */
29827 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
29828 struct RowSetChunk *pChunk, *pNextChunk;
29829 for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
29830 pNextChunk = pChunk->pNext;
29831 sqlite3DbFree(p->db, pChunk);
29832 }
29833 p->pChunk = 0;
29834 p->nFresh = 0;
29835 p->pEntry = 0;
29836 p->pLast = 0;
 
29837 p->isSorted = 1;
29838 }
29839
29840 /*
29841 ** Insert a new value into a RowSet.
@@ -29842,128 +29995,265 @@
29842 **
29843 ** The mallocFailed flag of the database connection is set if a
29844 ** memory allocation fails.
29845 */
29846 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
29847 struct RowSetEntry *pEntry;
29848 struct RowSetEntry *pLast;
29849 assert( p!=0 );
29850 if( p->nFresh==0 ){
29851 struct RowSetChunk *pNew;
29852 pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
29853 if( pNew==0 ){
29854 return;
29855 }
29856 pNew->pNext = p->pChunk;
29857 p->pChunk = pNew;
29858 p->pFresh = pNew->aEntry;
29859 p->nFresh = ROWSET_ENTRY_PER_CHUNK;
29860 }
29861 pEntry = p->pFresh++;
29862 p->nFresh--;
29863 pEntry->v = rowid;
29864 pEntry->pNext = 0;
29865 pLast = p->pLast;
29866 if( pLast ){
29867 if( p->isSorted && rowid<=pLast->v ){
29868 p->isSorted = 0;
29869 }
29870 pLast->pNext = pEntry;
29871 }else{
29872 assert( p->pEntry==0 );
29873 p->pEntry = pEntry;
29874 }
29875 p->pLast = pEntry;
29876 }
29877
29878 /*
29879 ** Merge two lists of RowSet entries. Remove duplicates.
29880 **
29881 ** The input lists are assumed to be in sorted order.
 
29882 */
29883 static struct RowSetEntry *boolidxMerge(
29884 struct RowSetEntry *pA, /* First sorted list to be merged */
29885 struct RowSetEntry *pB /* Second sorted list to be merged */
29886 ){
29887 struct RowSetEntry head;
29888 struct RowSetEntry *pTail;
29889
29890 pTail = &head;
29891 while( pA && pB ){
29892 assert( pA->pNext==0 || pA->v<=pA->pNext->v );
29893 assert( pB->pNext==0 || pB->v<=pB->pNext->v );
29894 if( pA->v<pB->v ){
29895 pTail->pNext = pA;
29896 pA = pA->pNext;
29897 pTail = pTail->pNext;
29898 }else if( pB->v<pA->v ){
29899 pTail->pNext = pB;
29900 pB = pB->pNext;
29901 pTail = pTail->pNext;
29902 }else{
29903 pA = pA->pNext;
29904 }
29905 }
29906 if( pA ){
29907 assert( pA->pNext==0 || pA->v<=pA->pNext->v );
29908 pTail->pNext = pA;
29909 }else{
29910 assert( pB==0 || pB->pNext==0 || pB->v<=pB->pNext->v );
29911 pTail->pNext = pB;
29912 }
29913 return head.pNext;
29914 }
29915
29916 /*
29917 ** Sort all elements of the RowSet into ascending order.
29918 */
29919 static void sqlite3RowSetSort(RowSet *p){
29920 unsigned int i;
29921 struct RowSetEntry *pEntry;
29922 struct RowSetEntry *aBucket[40];
29923
29924 assert( p->isSorted==0 );
29925 memset(aBucket, 0, sizeof(aBucket));
29926 while( p->pEntry ){
29927 pEntry = p->pEntry;
29928 p->pEntry = pEntry->pNext;
29929 pEntry->pNext = 0;
29930 for(i=0; aBucket[i]; i++){
29931 pEntry = boolidxMerge(aBucket[i],pEntry);
29932 aBucket[i] = 0;
29933 }
29934 aBucket[i] = pEntry;
29935 }
29936 pEntry = 0;
29937 for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
29938 pEntry = boolidxMerge(pEntry,aBucket[i]);
29939 }
29940 p->pEntry = pEntry;
29941 p->pLast = 0;
29942 p->isSorted = 1;
29943 }
 
29944
29945 /*
29946 ** Extract the next (smallest) element from the RowSet.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29947 ** Write the element into *pRowid. Return 1 on success. Return
29948 ** 0 if the RowSet is already empty.
 
 
 
29949 */
29950 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
29951 if( !p->isSorted ){
29952 sqlite3RowSetSort(p);
29953 }
29954 if( p->pEntry ){
29955 *pRowid = p->pEntry->v;
29956 p->pEntry = p->pEntry->pNext;
29957 if( p->pEntry==0 ){
29958 sqlite3RowSetClear(p);
29959 }
29960 return 1;
29961 }else{
29962 return 0;
29963 }
29964 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29965
29966 /************** End of rowset.c **********************************************/
29967 /************** Begin file pager.c *******************************************/
29968 /*
29969 ** 2001 September 15
@@ -29983,11 +30273,11 @@
29983 ** is separate from the database file. The pager also implements file
29984 ** locking to prevent two processes from writing the same database
29985 ** file simultaneously, or one process from reading the database while
29986 ** another is writing.
29987 **
29988 ** @(#) $Id: pager.c,v 1.580 2009/04/11 16:27:50 drh Exp $
29989 */
29990 #ifndef SQLITE_OMIT_DISKIO
29991
29992 /*
29993 ** Macros for troubleshooting. Normally turned off
@@ -30193,10 +30483,16 @@
30193 ** needSync
30194 **
30195 ** TODO: It might be easier to set this variable in writeJournalHdr()
30196 ** and writeMasterJournal() only. Change its meaning to "unsynced data
30197 ** has been written to the journal".
 
 
 
 
 
 
30198 */
30199 struct Pager {
30200 sqlite3_vfs *pVfs; /* OS functions to use for IO */
30201 u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
30202 u8 journalMode; /* On of the PAGER_JOURNALMODE_* values */
@@ -30226,10 +30522,11 @@
30226 u8 journalStarted; /* True if header of journal is synced */
30227 u8 changeCountDone; /* Set after incrementing the change-counter */
30228 u8 setMaster; /* True if a m-j name has been written to jrnl */
30229 u8 doNotSync; /* Boolean. While true, do not spill the cache */
30230 u8 dbSizeValid; /* Set when dbSize is correct */
 
30231 Pgno dbSize; /* Number of pages in the database */
30232 Pgno dbOrigSize; /* dbSize before the current transaction */
30233 Pgno dbFileSize; /* Number of pages in the database file */
30234 int errCode; /* One of several kinds of errors */
30235 int nRec; /* Pages journalled since last j-header written */
@@ -31005,10 +31302,11 @@
31005 */
31006 static void pager_reset(Pager *pPager){
31007 if( SQLITE_OK==pPager->errCode ){
31008 sqlite3BackupRestart(pPager->pBackup);
31009 sqlite3PcacheClear(pPager->pPCache);
 
31010 }
31011 }
31012
31013 /*
31014 ** Free all structures in the Pager.aSavepoint[] array and set both
@@ -31018,11 +31316,11 @@
31018 static void releaseAllSavepoints(Pager *pPager){
31019 int ii; /* Iterator for looping through Pager.aSavepoint */
31020 for(ii=0; ii<pPager->nSavepoint; ii++){
31021 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
31022 }
31023 if( !pPager->exclusiveMode ){
31024 sqlite3OsClose(pPager->sjfd);
31025 }
31026 sqlite3_free(pPager->aSavepoint);
31027 pPager->aSavepoint = 0;
31028 pPager->nSavepoint = 0;
@@ -31254,11 +31552,15 @@
31254 sqlite3OsClose(pPager->jfd);
31255 if( !isMemoryJournal ){
31256 rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
31257 }
31258 }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
31259 rc = sqlite3OsTruncate(pPager->jfd, 0);
 
 
 
 
31260 pPager->journalOff = 0;
31261 pPager->journalStarted = 0;
31262 }else if( pPager->exclusiveMode
31263 || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
31264 ){
@@ -33143,11 +33445,11 @@
33143 ROUND8(pVfs->szOsFile) + /* The main db file */
33144 journalFileSize * 2 + /* The two journal files */
33145 nPathname + 1 + /* zFilename */
33146 nPathname + 8 + 1 /* zJournal */
33147 );
33148 assert( EIGHT_BYTE_ALIGNMENT(journalFileSize) );
33149 if( !pPtr ){
33150 sqlite3_free(zPathname);
33151 return SQLITE_NOMEM;
33152 }
33153 pPager = (Pager*)(pPtr);
@@ -33628,13 +33930,19 @@
33628 }
33629
33630 /*
33631 ** If the reference count has reached zero, rollback any active
33632 ** transaction and unlock the pager.
 
 
 
 
33633 */
33634 static void pagerUnlockIfUnused(Pager *pPager){
33635 if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
 
 
33636 pagerUnlockAndRollback(pPager);
33637 }
33638 }
33639
33640 /*
@@ -33858,11 +34166,11 @@
33858 ** sqlite3OsOpen() fails.
33859 */
33860 static int openSubJournal(Pager *pPager){
33861 int rc = SQLITE_OK;
33862 if( isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ){
33863 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
33864 sqlite3MemJournalOpen(pPager->sjfd);
33865 }else{
33866 rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
33867 }
33868 }
@@ -33977,14 +34285,23 @@
33977 ** of the journal file is deferred until there is an actual need to
33978 ** write to the journal. TODO: Why handle temporary files differently?
33979 **
33980 ** If the journal file is opened (or if it is already open), then a
33981 ** journal-header is written to the start of it.
 
 
 
 
 
 
 
 
33982 */
33983 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag){
33984 int rc = SQLITE_OK;
33985 assert( pPager->state!=PAGER_UNLOCK );
 
33986 if( pPager->state==PAGER_SHARED ){
33987 assert( pPager->pInJournal==0 );
33988 assert( !MEMDB && !pPager->tempFile );
33989
33990 /* Obtain a RESERVED lock on the database file. If the exFlag parameter
@@ -34065,11 +34382,11 @@
34065 **
34066 ** First check to see that the transaction journal exists and
34067 ** create it if it does not.
34068 */
34069 assert( pPager->state!=PAGER_UNLOCK );
34070 rc = sqlite3PagerBegin(pPager, 0);
34071 if( rc!=SQLITE_OK ){
34072 return rc;
34073 }
34074 assert( pPager->state>=PAGER_RESERVED );
34075 if( !isOpen(pPager->jfd) && pPager->useJournal
@@ -35148,15 +35465,18 @@
35148 ** PAGER_JOURNALMODE_TRUNCATE
35149 ** PAGER_JOURNALMODE_PERSIST
35150 ** PAGER_JOURNALMODE_OFF
35151 ** PAGER_JOURNALMODE_MEMORY
35152 **
35153 ** If the parameter is not _QUERY, then the journal-mode is set to the
35154 ** value specified. Except, an in-memory database can only have its
35155 ** journal mode set to _OFF or _MEMORY. Attempts to change the journal
35156 ** mode of an in-memory database to something other than _OFF or _MEMORY
35157 ** are silently ignored.
 
 
 
35158 **
35159 ** The returned indicate the current (possibly updated) journal-mode.
35160 */
35161 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
35162 assert( eMode==PAGER_JOURNALMODE_QUERY
@@ -35164,12 +35484,19 @@
35164 || eMode==PAGER_JOURNALMODE_TRUNCATE
35165 || eMode==PAGER_JOURNALMODE_PERSIST
35166 || eMode==PAGER_JOURNALMODE_OFF
35167 || eMode==PAGER_JOURNALMODE_MEMORY );
35168 assert( PAGER_JOURNALMODE_QUERY<0 );
35169 if( eMode>=0 && (!MEMDB || eMode==PAGER_JOURNALMODE_MEMORY
35170 || eMode==PAGER_JOURNALMODE_OFF) ){
 
 
 
 
 
 
 
35171 pPager->journalMode = (u8)eMode;
35172 }
35173 return (int)pPager->journalMode;
35174 }
35175
@@ -36210,11 +36537,11 @@
36210 ** May you do good and not evil.
36211 ** May you find forgiveness for yourself and forgive others.
36212 ** May you share freely, never taking more than you give.
36213 **
36214 *************************************************************************
36215 ** $Id: btree.c,v 1.595 2009/04/11 16:06:15 danielk1977 Exp $
36216 **
36217 ** This file implements a external (disk-based) database using BTrees.
36218 ** See the header comment on "btreeInt.h" for additional information.
36219 ** Including a description of file format and an overview of operation.
36220 */
@@ -36962,22 +37289,63 @@
36962 ** Compute the total number of bytes that a Cell needs in the cell
36963 ** data area of the btree-page. The return number includes the cell
36964 ** data header and the local payload, but not any overflow page or
36965 ** the space used by the cell pointer.
36966 */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36967 #ifndef NDEBUG
36968 static u16 cellSize(MemPage *pPage, int iCell){
36969 CellInfo info;
36970 sqlite3BtreeParseCell(pPage, iCell, &info);
36971 return info.nSize;
36972 }
36973 #endif
36974 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
36975 CellInfo info;
36976 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
36977 return info.nSize;
36978 }
36979
36980 #ifndef SQLITE_OMIT_AUTOVACUUM
36981 /*
36982 ** If the cell pCell, part of page pPage contains a pointer
36983 ** to an overflow page, insert an entry into the pointer-map
@@ -37120,17 +37488,17 @@
37120 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
37121 int size = get2byte(&data[pc+2]); /* Size of free slot */
37122 if( size>=nByte ){
37123 int x = size - nByte;
37124 if( x<4 ){
37125 /* Remove the slot from the free-list. Update the number of
37126 ** fragmented bytes within the page. */
37127 memcpy(&data[addr], &data[pc], 2);
37128 data[hdr+7] = (u8)(nFrag + x);
37129 }else{
37130 /* The slot remains on the free-list. Reduce its size to account
37131 ** for the portion used by the new allocation. */
37132 put2byte(&data[pc+2], x);
37133 }
37134 return pc + x;
37135 }
37136 }
@@ -37560,10 +37928,16 @@
37560 ** zFilename is the name of the database file. If zFilename is NULL
37561 ** a new database with a random name is created. This randomly named
37562 ** database file will be deleted when sqlite3BtreeClose() is called.
37563 ** If zFilename is ":memory:" then an in-memory database is created
37564 ** that is automatically destroyed when it is closed.
 
 
 
 
 
 
37565 */
37566 SQLITE_PRIVATE int sqlite3BtreeOpen(
37567 const char *zFilename, /* Name of the file containing the BTree database */
37568 sqlite3 *db, /* Associated database handle */
37569 Btree **ppBtree, /* Pointer to new Btree object written here */
@@ -37625,10 +37999,21 @@
37625 sqlite3_mutex_enter(mutexShared);
37626 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
37627 assert( pBt->nRef>0 );
37628 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
37629 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
 
 
 
 
 
 
 
 
 
 
 
37630 p->pBt = pBt;
37631 pBt->nRef++;
37632 break;
37633 }
37634 }
@@ -37682,11 +38067,10 @@
37682 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
37683 pBt->pageSize = get2byte(&zDbHeader[16]);
37684 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
37685 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
37686 pBt->pageSize = 0;
37687 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
37688 #ifndef SQLITE_OMIT_AUTOVACUUM
37689 /* If the magic name ":memory:" will create an in-memory database, then
37690 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
37691 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
37692 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
@@ -37704,13 +38088,14 @@
37704 #ifndef SQLITE_OMIT_AUTOVACUUM
37705 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
37706 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
37707 #endif
37708 }
 
 
37709 pBt->usableSize = pBt->pageSize - nReserve;
37710 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
37711 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
37712
37713 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
37714 /* Add the new BtShared object to the linked list sharable BtShareds.
37715 */
37716 if( p->sharable ){
@@ -38150,11 +38535,12 @@
38150 */
38151 releasePage(pPage1);
38152 pBt->usableSize = (u16)usableSize;
38153 pBt->pageSize = (u16)pageSize;
38154 freeTempSpace(pBt);
38155 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
 
38156 return SQLITE_OK;
38157 }
38158 if( usableSize<500 ){
38159 goto page1_init_failed;
38160 }
@@ -38229,18 +38615,10 @@
38229 static void unlockBtreeIfUnused(BtShared *pBt){
38230 assert( sqlite3_mutex_held(pBt->mutex) );
38231 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
38232 if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
38233 assert( pBt->pPage1->aData );
38234 #if 0
38235 if( pBt->pPage1->aData==0 ){
38236 MemPage *pPage = pBt->pPage1;
38237 pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
38238 pPage->pBt = pBt;
38239 pPage->pgno = 1;
38240 }
38241 #endif
38242 releasePage(pBt->pPage1);
38243 }
38244 pBt->pPage1 = 0;
38245 }
38246 }
@@ -38379,11 +38757,11 @@
38379
38380 if( rc==SQLITE_OK && wrflag ){
38381 if( pBt->readOnly ){
38382 rc = SQLITE_READONLY;
38383 }else{
38384 rc = sqlite3PagerBegin(pBt->pPager, wrflag>1);
38385 if( rc==SQLITE_OK ){
38386 rc = newDatabase(pBt);
38387 }
38388 }
38389 }
@@ -38829,11 +39207,11 @@
38829 ** the journal. Then the contents of the journal are flushed out to
38830 ** the disk. After the journal is safely on oxide, the changes to the
38831 ** database are written into the database file and flushed to oxide.
38832 ** At the end of this call, the rollback journal still exists on the
38833 ** disk and we are still holding all locks, so the transaction has not
38834 ** committed. See sqlite3BtreeCommit() for the second phase of the
38835 ** commit process.
38836 **
38837 ** This call is a no-op if no write-transaction is currently active on pBt.
38838 **
38839 ** Otherwise, sync the database file for the btree pBt. zMaster points to
@@ -38869,16 +39247,17 @@
38869
38870 /*
38871 ** Commit the transaction currently in progress.
38872 **
38873 ** This routine implements the second phase of a 2-phase commit. The
38874 ** sqlite3BtreeSync() routine does the first phase and should be invoked
38875 ** prior to calling this routine. The sqlite3BtreeSync() routine did
38876 ** all the work of writing information out to disk and flushing the
38877 ** contents so that they are written onto the disk platter. All this
38878 ** routine has to do is delete or truncate the rollback journal
38879 ** (which causes the transaction to commit) and drop locks.
 
38880 **
38881 ** This will release the write lock on the database file. If there
38882 ** are no active cursors, it also releases the read lock.
38883 */
38884 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
@@ -38913,11 +39292,11 @@
38913 if( 0==pBt->nTransaction ){
38914 pBt->inTransaction = TRANS_NONE;
38915 }
38916 }
38917
38918 /* Set the handles current transaction state to TRANS_NONE and unlock
38919 ** the pager if this call closed the only read or write transaction.
38920 */
38921 btreeClearHasContent(pBt);
38922 p->inTrans = TRANS_NONE;
38923 unlockBtreeIfUnused(pBt);
@@ -40069,20 +40448,35 @@
40069 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
40070 int rc;
40071
40072 assert( cursorHoldsMutex(pCur) );
40073 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40074 rc = moveToRoot(pCur);
40075 if( rc==SQLITE_OK ){
40076 if( CURSOR_INVALID==pCur->eState ){
40077 assert( pCur->apPage[pCur->iPage]->nCell==0 );
40078 *pRes = 1;
40079 }else{
40080 assert( pCur->eState==CURSOR_VALID );
40081 *pRes = 0;
40082 rc = moveToRightmost(pCur);
40083 getCellInfo(pCur);
40084 pCur->atLast = rc==SQLITE_OK ?1:0;
40085 }
40086 }
40087 return rc;
40088 }
@@ -40169,18 +40563,17 @@
40169 pCur->aiIdx[pCur->iPage] = (u16)upr;
40170 }else{
40171 pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
40172 }
40173 for(;;){
40174 void *pCellKey;
40175 i64 nCellKey;
40176 int idx = pCur->aiIdx[pCur->iPage];
40177 pCur->info.nSize = 0;
40178 pCur->validNKey = 1;
40179 if( pPage->intKey ){
40180 u8 *pCell;
40181 pCell = findCell(pPage, idx) + pPage->childPtrSize;
40182 if( pPage->hasData ){
40183 u32 dummy;
40184 pCell += getVarint32(pCell, dummy);
40185 }
40186 getVarint(pCell, (u64*)&nCellKey);
@@ -40190,30 +40583,54 @@
40190 c = -1;
40191 }else{
40192 assert( nCellKey>intKey );
40193 c = +1;
40194 }
40195 }else{
40196 int available;
40197 pCellKey = (void *)fetchPayload(pCur, &available, 0);
40198 nCellKey = pCur->info.nKey;
40199 if( available>=nCellKey ){
40200 c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
40201 }else{
40202 pCellKey = sqlite3Malloc( (int)nCellKey );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40203 if( pCellKey==0 ){
40204 rc = SQLITE_NOMEM;
40205 goto moveto_finish;
40206 }
40207 rc = sqlite3BtreeKey(pCur, 0, (int)nCellKey, (void*)pCellKey);
40208 c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
40209 sqlite3_free(pCellKey);
40210 if( rc ) goto moveto_finish;
40211 }
40212 }
40213 if( c==0 ){
40214 pCur->info.nKey = nCellKey;
40215 if( pPage->intKey && !pPage->leaf ){
40216 lwr = idx;
40217 upr = lwr - 1;
40218 break;
40219 }else{
@@ -40226,11 +40643,10 @@
40226 lwr = idx+1;
40227 }else{
40228 upr = idx-1;
40229 }
40230 if( lwr>upr ){
40231 pCur->info.nKey = nCellKey;
40232 break;
40233 }
40234 pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
40235 }
40236 assert( lwr==upr+1 );
@@ -41187,11 +41603,11 @@
41187 ** the entry for the overflow page into the pointer map.
41188 */
41189 CellInfo info;
41190 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
41191 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
41192 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
41193 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
41194 rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
41195 if( rc!=SQLITE_OK ) return rc;
41196 }
41197 }
@@ -41210,43 +41626,36 @@
41210 int nCell, /* The number of cells to add to this page */
41211 u8 **apCell, /* Pointers to cell bodies */
41212 u16 *aSize /* Sizes of the cells */
41213 ){
41214 int i; /* Loop counter */
41215 int totalSize; /* Total size of all cells */
41216 int hdr; /* Index of page header */
41217 int cellptr; /* Address of next cell pointer */
41218 int cellbody; /* Address of next cell body */
41219 u8 *data; /* Data for the page */
 
 
41220
41221 assert( pPage->nOverflow==0 );
41222 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
41223 assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
41224 totalSize = 0;
41225 for(i=0; i<nCell; i++){
41226 totalSize += aSize[i];
41227 }
41228 assert( totalSize+2*nCell<=pPage->nFree );
41229 assert( pPage->nCell==0 );
41230 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
41231 cellptr = pPage->cellOffset;
41232 data = pPage->aData;
41233 hdr = pPage->hdrOffset;
 
 
 
 
 
 
41234 put2byte(&data[hdr+3], nCell);
41235 if( nCell ){
41236 cellbody = allocateSpace(pPage, totalSize);
41237 assert( cellbody>0 );
41238 assert( pPage->nFree >= 2*nCell );
41239 pPage->nFree -= 2*nCell;
41240 for(i=0; i<nCell; i++){
41241 put2byte(&data[cellptr], cellbody);
41242 memcpy(&data[cellbody], apCell[i], aSize[i]);
41243 cellptr += 2;
41244 cellbody += aSize[i];
41245 }
41246 assert( cellbody==pPage->pBt->usableSize );
41247 }
41248 pPage->nCell = (u16)nCell;
41249 }
41250
41251 /*
41252 ** The following parameters determine how many adjacent pages get involved
@@ -42274,20 +42683,32 @@
42274 ** define what table the record should be inserted into. The cursor
42275 ** is left pointing at a random location.
42276 **
42277 ** For an INTKEY table, only the nKey value of the key is used. pKey is
42278 ** ignored. For a ZERODATA table, the pData and nData are both ignored.
 
 
 
 
 
 
 
 
 
 
 
42279 */
42280 SQLITE_PRIVATE int sqlite3BtreeInsert(
42281 BtCursor *pCur, /* Insert data into the table of this cursor */
42282 const void *pKey, i64 nKey, /* The key of the new record */
42283 const void *pData, int nData, /* The data of the new record */
42284 int nZero, /* Number of extra 0 bytes to append to data */
42285 int appendBias /* True if this is likely an append */
 
42286 ){
42287 int rc;
42288 int loc;
42289 int szNew;
42290 int idx;
42291 MemPage *pPage;
42292 Btree *p = pCur->pBtree;
42293 BtShared *pBt = p->pBt;
@@ -42306,16 +42727,25 @@
42306 }
42307 if( pCur->eState==CURSOR_FAULT ){
42308 return pCur->skip;
42309 }
42310
42311 /* Save the positions of any other cursors open on this table */
42312 sqlite3BtreeClearCursor(pCur);
42313 if(
42314 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
 
 
 
 
 
 
 
 
 
42315 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
42316 ){
42317 return rc;
42318 }
42319
42320 pPage = pCur->apPage[pCur->iPage];
42321 assert( pPage->intKey || nKey>=0 );
@@ -42357,21 +42787,46 @@
42357 pCur->validNKey = 0;
42358 }else{
42359 assert( pPage->leaf );
42360 }
42361 rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
42362 if( rc==SQLITE_OK ){
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42363 rc = balance(pCur, 1);
 
 
 
42364 }
42365
42366 /* Must make sure nOverflow is reset to zero even if the balance()
42367 ** fails. Internal data structure corruption will result otherwise. */
42368 pCur->apPage[pCur->iPage]->nOverflow = 0;
42369
42370 if( rc==SQLITE_OK ){
42371 moveToRoot(pCur);
42372 }
42373 end_insert:
42374 return rc;
42375 }
42376
42377 /*
@@ -43199,11 +43654,11 @@
43199 u8 ePtrmapType;
43200 Pgno iPtrmapParent;
43201
43202 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
43203 if( rc!=SQLITE_OK ){
43204 if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
43205 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
43206 return;
43207 }
43208
43209 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
@@ -43326,11 +43781,11 @@
43326 pBt = pCheck->pBt;
43327 usableSize = pBt->usableSize;
43328 if( iPage==0 ) return 0;
43329 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
43330 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
43331 if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
43332 checkAppendMsg(pCheck, zContext,
43333 "unable to get the page. error code=%d", rc);
43334 return 0;
43335 }
43336 if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
@@ -44398,11 +44853,11 @@
44398 ** This file contains code use to manipulate "Mem" structure. A "Mem"
44399 ** stores a single value in the VDBE. Mem is an opaque structure visible
44400 ** only within the VDBE. Interface routines refer to a Mem using the
44401 ** name sqlite_value
44402 **
44403 ** $Id: vdbemem.c,v 1.140 2009/04/05 12:22:09 drh Exp $
44404 */
44405
44406 /*
44407 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
44408 ** P if required.
@@ -44651,20 +45106,22 @@
44651 ** invoking an external callback, free it now. Calling this function
44652 ** does not free any Mem.zMalloc buffer.
44653 */
44654 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
44655 assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
44656 if( p->flags&MEM_Agg ){
44657 sqlite3VdbeMemFinalize(p, p->u.pDef);
44658 assert( (p->flags & MEM_Agg)==0 );
44659 sqlite3VdbeMemRelease(p);
44660 }else if( p->flags&MEM_Dyn && p->xDel ){
44661 assert( (p->flags&MEM_RowSet)==0 );
44662 p->xDel((void *)p->z);
44663 p->xDel = 0;
44664 }else if( p->flags&MEM_RowSet ){
44665 sqlite3RowSetClear(p->u.pRowSet);
 
 
44666 }
44667 }
44668
44669 /*
44670 ** Release any memory held by the Mem. This may leave the Mem in an
@@ -45356,16 +45813,18 @@
45356
45357 if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
45358 zVal = sqlite3DbStrNDup(db, (char*)pExpr->token.z, pExpr->token.n);
45359 pVal = sqlite3ValueNew(db);
45360 if( !zVal || !pVal ) goto no_mem;
45361 sqlite3Dequote(zVal);
45362 sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
45363 if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
45364 sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, enc);
45365 }else{
45366 sqlite3ValueApplyAffinity(pVal, affinity, enc);
 
 
 
45367 }
45368 }else if( op==TK_UMINUS ) {
45369 if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
45370 pVal->u.i = -1 * pVal->u.i;
45371 /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
@@ -45453,11 +45912,11 @@
45453 ** This file contains code used for creating, destroying, and populating
45454 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
45455 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
45456 ** But that file was getting too big so this subroutines were split out.
45457 **
45458 ** $Id: vdbeaux.c,v 1.451 2009/04/10 15:42:36 shane Exp $
45459 */
45460
45461
45462
45463 /*
@@ -46167,13 +46626,13 @@
46167 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
46168 **
46169 */
46170 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
46171 int mask;
46172 assert( i>=0 && i<p->db->nDb );
46173 assert( i<(int)sizeof(p->btreeMask)*8 );
46174 mask = 1<<i;
46175 if( (p->btreeMask & mask)==0 ){
46176 p->btreeMask |= mask;
46177 sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
46178 }
46179 }
@@ -47377,11 +47836,11 @@
47377 */
47378 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
47379 int i;
47380 for(i=0; i<pVdbeFunc->nAux; i++){
47381 struct AuxData *pAux = &pVdbeFunc->apAux[i];
47382 if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
47383 if( pAux->xDelete ){
47384 pAux->xDelete(pAux->pAux);
47385 }
47386 pAux->pAux = 0;
47387 }
@@ -47439,12 +47898,12 @@
47439 #endif
47440 assert( p->isTable );
47441 rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
47442 if( rc ) return rc;
47443 p->lastRowid = keyToInt(p->movetoTarget);
47444 p->rowidIsValid = res==0 ?1:0;
47445 if( res<0 ){
47446 rc = sqlite3BtreeNext(p->pCursor, &res);
47447 if( rc ) return rc;
47448 }
47449 #ifdef SQLITE_TEST
47450 sqlite3_search_count++;
@@ -47903,10 +48362,11 @@
47903
47904 pKeyInfo = pPKey2->pKeyInfo;
47905 mem1.enc = pKeyInfo->enc;
47906 mem1.db = pKeyInfo->db;
47907 mem1.flags = 0;
 
47908 mem1.zMalloc = 0;
47909
47910 idx1 = getVarint32(aKey1, szHdr1);
47911 d1 = szHdr1;
47912 if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
@@ -47932,10 +48392,22 @@
47932 break;
47933 }
47934 i++;
47935 }
47936 if( mem1.zMalloc ) sqlite3VdbeMemRelease(&mem1);
 
 
 
 
 
 
 
 
 
 
 
 
47937
47938 if( rc==0 ){
47939 /* rc==0 here means that one of the keys ran out of fields and
47940 ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
47941 ** flag is set, then break the tie by treating key2 as larger.
@@ -48133,11 +48605,11 @@
48133 *************************************************************************
48134 **
48135 ** This file contains code use to implement APIs that are part of the
48136 ** VDBE.
48137 **
48138 ** $Id: vdbeapi.c,v 1.161 2009/04/10 23:11:31 drh Exp $
48139 */
48140
48141 #if 0 && defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
48142 /*
48143 ** The following structure contains pointers to the end points of a
@@ -48518,10 +48990,14 @@
48518 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
48519 sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
48520 }
48521 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
48522 pCtx->isError = errCode;
 
 
 
 
48523 }
48524
48525 /* Force an SQLITE_TOOBIG error. */
48526 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
48527 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
@@ -49270,19 +49746,36 @@
49270 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
49271 }
49272 #endif /* SQLITE_OMIT_UTF16 */
49273 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
49274 int rc;
49275 Vdbe *p = (Vdbe *)pStmt;
49276 rc = vdbeUnbind(p, i);
49277 if( rc==SQLITE_OK ){
49278 rc = sqlite3VdbeMemCopy(&p->aVar[i-1], pValue);
49279 if( rc==SQLITE_OK ){
49280 rc = sqlite3VdbeChangeEncoding(&p->aVar[i-1], ENC(p->db));
49281 }
49282 sqlite3_mutex_leave(p->db->mutex);
49283 rc = sqlite3ApiExit(p->db, rc);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49284 }
49285 return rc;
49286 }
49287 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
49288 int rc;
@@ -49491,11 +49984,11 @@
49491 ** documentation, headers files, or other derived files. The formatting
49492 ** of the code in this file is, therefore, important. See other comments
49493 ** in this file for details. If in doubt, do not deviate from existing
49494 ** commenting and indentation practices when changing or adding code.
49495 **
49496 ** $Id: vdbe.c,v 1.832 2009/04/10 12:55:17 danielk1977 Exp $
49497 */
49498
49499 /*
49500 ** The following global variable is incremented every time a cursor
49501 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
@@ -49874,10 +50367,12 @@
49874 fprintf(out, " si:%lld", p->u.i);
49875 }else if( p->flags & MEM_Int ){
49876 fprintf(out, " i:%lld", p->u.i);
49877 }else if( p->flags & MEM_Real ){
49878 fprintf(out, " r:%g", p->r);
 
 
49879 }else{
49880 char zBuf[200];
49881 sqlite3VdbeMemPrettyPrint(p, zBuf);
49882 fprintf(out, " ");
49883 fprintf(out, "%s", zBuf);
@@ -51999,11 +52494,11 @@
51999 if( db->autoCommit ){
52000 db->autoCommit = 0;
52001 db->isTransactionSavepoint = 1;
52002 }else{
52003 db->nSavepoint++;
52004 }
52005
52006 /* Link the new savepoint into the database handle's list. */
52007 pNew->pNext = db->pSavepoint;
52008 db->pSavepoint = pNew;
52009 }
@@ -52873,107 +53368,86 @@
52873 break;
52874 }
52875
52876 /* Opcode: IsUnique P1 P2 P3 P4 *
52877 **
52878 ** The P3 register contains an integer record number. Call this
52879 ** record number R. The P4 register contains an index key created
52880 ** using MakeRecord. Call it K.
52881 **
52882 ** P1 is an index. So it has no data and its key consists of a
52883 ** record generated by OP_MakeRecord where the last field is the
52884 ** rowid of the entry that the index refers to.
52885 **
52886 ** This instruction asks if there is an entry in P1 where the
52887 ** fields matches K but the rowid is different from R.
52888 ** If there is no such entry, then there is an immediate
52889 ** jump to P2. If any entry does exist where the index string
52890 ** matches K but the record number is not R, then the record
52891 ** number for that entry is written into P3 and control
52892 ** falls through to the next instruction.
 
 
 
 
 
 
 
 
 
52893 **
52894 ** See also: NotFound, NotExists, Found
52895 */
52896 case OP_IsUnique: { /* jump, in3 */
52897 int i = pOp->p1;
52898 VdbeCursor *pCx;
52899 BtCursor *pCrsr;
52900 Mem *pK;
52901 i64 R;
52902
52903 /* Pop the value R off the top of the stack
52904 */
52905 assert( pOp->p4type==P4_INT32 );
52906 assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
52907 pK = &p->aMem[pOp->p4.i];
52908 sqlite3VdbeMemIntegerify(pIn3);
52909 R = pIn3->u.i;
52910 assert( i>=0 && i<p->nCursor );
52911 pCx = p->apCsr[i];
52912 assert( pCx!=0 );
52913 pCrsr = pCx->pCursor;
52914 if( pCrsr!=0 ){
52915 int res;
52916 i64 v; /* The record number that matches K */
52917 UnpackedRecord *pIdxKey; /* Unpacked version of P4 */
52918
52919 /* Make sure K is a string and make zKey point to K
52920 */
52921 assert( pK->flags & MEM_Blob );
52922 pIdxKey = sqlite3VdbeRecordUnpack(pCx->pKeyInfo, pK->n, pK->z,
52923 aTempRec, sizeof(aTempRec));
52924 if( pIdxKey==0 ){
52925 goto no_mem;
52926 }
52927 pIdxKey->flags |= UNPACKED_IGNORE_ROWID;
52928
52929 /* Search for an entry in P1 where all but the last rowid match K
52930 ** If there is no such entry, jump immediately to P2.
52931 */
52932 assert( pCx->deferredMoveto==0 );
52933 pCx->cacheStatus = CACHE_STALE;
52934 rc = sqlite3BtreeMovetoUnpacked(pCrsr, pIdxKey, 0, 0, &res);
52935 if( rc!=SQLITE_OK ){
52936 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
52937 goto abort_due_to_error;
52938 }
52939 if( res<0 ){
52940 rc = sqlite3BtreeNext(pCrsr, &res);
52941 if( res ){
52942 pc = pOp->p2 - 1;
52943 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
52944 break;
52945 }
52946 }
52947 rc = sqlite3VdbeIdxKeyCompare(pCx, pIdxKey, &res);
52948 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
52949 if( rc!=SQLITE_OK ) goto abort_due_to_error;
52950 if( res>0 ){
52951 pc = pOp->p2 - 1;
52952 break;
52953 }
52954
52955 /* At this point, pCrsr is pointing to an entry in P1 where all but
52956 ** the final entry (the rowid) matches K. Check to see if the
52957 ** final rowid column is different from R. If it equals R then jump
52958 ** immediately to P2.
52959 */
52960 rc = sqlite3VdbeIdxRowid(pCrsr, &v);
52961 if( rc!=SQLITE_OK ){
52962 goto abort_due_to_error;
52963 }
52964 if( v==R ){
52965 pc = pOp->p2 - 1;
52966 break;
52967 }
52968
52969 /* The final varint of the key is different from R. Store it back
52970 ** into register R3. (The record number of an entry that violates
52971 ** a UNIQUE constraint.)
52972 */
52973 pIn3->u.i = v;
52974 assert( pIn3->flags&MEM_Int );
52975 }
52976 break;
52977 }
52978
52979 /* Opcode: NotExists P1 P2 P3 * *
@@ -53000,26 +53474,29 @@
53000 int res = 0;
53001 u64 iKey;
53002 assert( pIn3->flags & MEM_Int );
53003 assert( p->apCsr[i]->isTable );
53004 iKey = intToKey(pIn3->u.i);
53005 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0,&res);
53006 pC->lastRowid = pIn3->u.i;
53007 pC->rowidIsValid = res==0 ?1:0;
53008 pC->nullRow = 0;
53009 pC->cacheStatus = CACHE_STALE;
 
53010 if( res!=0 ){
53011 pc = pOp->p2 - 1;
53012 assert( pC->rowidIsValid==0 );
53013 }
 
53014 }else if( !pC->pseudoTable ){
53015 /* This happens when an attempt to open a read cursor on the
53016 ** sqlite_master table returns SQLITE_EMPTY.
53017 */
53018 assert( pC->isTable );
53019 pc = pOp->p2 - 1;
53020 assert( pC->rowidIsValid==0 );
 
53021 }
53022 break;
53023 }
53024
53025 /* Opcode: Sequence P1 P2 * * *
@@ -53258,19 +53735,21 @@
53258 pC->pData[pC->nData+1] = 0;
53259 }
53260 pC->nullRow = 0;
53261 }else{
53262 int nZero;
 
53263 if( pData->flags & MEM_Zero ){
53264 nZero = pData->u.nZero;
53265 }else{
53266 nZero = 0;
53267 }
53268 sqlite3BtreeSetCachedRowid(pC->pCursor, 0);
53269 rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
53270 pData->z, pData->n, nZero,
53271 pOp->p5 & OPFLAG_APPEND);
 
53272 }
53273
53274 pC->rowidIsValid = 0;
53275 pC->deferredMoveto = 0;
53276 pC->cacheStatus = CACHE_STALE;
@@ -53430,32 +53909,54 @@
53430
53431 /* Opcode: Rowid P1 P2 * * *
53432 **
53433 ** Store in register P2 an integer which is the key of the table entry that
53434 ** P1 is currently point to.
 
 
 
 
53435 */
53436 case OP_Rowid: { /* out2-prerelease */
53437 int i = pOp->p1;
53438 VdbeCursor *pC;
53439 i64 v;
53440
53441 assert( i>=0 && i<p->nCursor );
53442 pC = p->apCsr[i];
53443 assert( pC!=0 );
53444 rc = sqlite3VdbeCursorMoveto(pC);
53445 if( rc ) goto abort_due_to_error;
53446 if( pC->rowidIsValid ){
53447 v = pC->lastRowid;
 
53448 }else if( pC->pseudoTable ){
53449 v = keyToInt(pC->iKey);
53450 }else if( pC->nullRow ){
53451 /* Leave the rowid set to a NULL */
53452 break;
 
 
 
 
 
 
 
 
 
 
 
53453 }else{
53454 assert( pC->pCursor!=0 );
53455 sqlite3BtreeKeySize(pC->pCursor, &v);
53456 v = keyToInt(v);
 
 
 
 
 
 
53457 }
53458 pOut->u.i = v;
53459 MemSetTypeFlag(pOut, MEM_Int);
53460 break;
53461 }
@@ -53615,11 +54116,11 @@
53615 }
53616 pC->rowidIsValid = 0;
53617 break;
53618 }
53619
53620 /* Opcode: IdxInsert P1 P2 P3 * *
53621 **
53622 ** Register P2 holds a SQL index key made using the
53623 ** MakeRecord instructions. This opcode writes that key
53624 ** into the index P1. Data for the entry is nil.
53625 **
@@ -53640,11 +54141,13 @@
53640 assert( pC->isTable==0 );
53641 rc = ExpandBlob(pIn2);
53642 if( rc==SQLITE_OK ){
53643 int nKey = pIn2->n;
53644 const char *zKey = pIn2->z;
53645 rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3);
 
 
53646 assert( pC->deferredMoveto==0 );
53647 pC->cacheStatus = CACHE_STALE;
53648 }
53649 }
53650 break;
@@ -54138,10 +54641,63 @@
54138 sqlite3VdbeMemSetInt64(pOut, val);
54139 }
54140 break;
54141 }
54142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54143
54144 #ifndef SQLITE_OMIT_TRIGGER
54145 /* Opcode: ContextPush * * *
54146 **
54147 ** Save the current Vdbe context such that it can be restored by a ContextPop
@@ -54569,41 +55125,10 @@
54569 }
54570 pCur->nullRow = 0;
54571
54572 break;
54573 }
54574 #endif /* SQLITE_OMIT_VIRTUALTABLE */
54575
54576 #ifndef SQLITE_OMIT_VIRTUALTABLE
54577 /* Opcode: VRowid P1 P2 * * *
54578 **
54579 ** Store into register P2 the rowid of
54580 ** the virtual-table that the P1 cursor is pointing to.
54581 */
54582 case OP_VRowid: { /* out2-prerelease */
54583 sqlite3_vtab *pVtab;
54584 const sqlite3_module *pModule;
54585 sqlite_int64 iRow;
54586 VdbeCursor *pCur = p->apCsr[pOp->p1];
54587
54588 assert( pCur->pVtabCursor );
54589 if( pCur->nullRow ){
54590 break;
54591 }
54592 pVtab = pCur->pVtabCursor->pVtab;
54593 pModule = pVtab->pModule;
54594 assert( pModule->xRowid );
54595 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
54596 rc = pModule->xRowid(pCur->pVtabCursor, &iRow);
54597 sqlite3DbFree(db, p->zErrMsg);
54598 p->zErrMsg = pVtab->zErrMsg;
54599 pVtab->zErrMsg = 0;
54600 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
54601 MemSetTypeFlag(pOut, MEM_Int);
54602 pOut->u.i = iRow;
54603 break;
54604 }
54605 #endif /* SQLITE_OMIT_VIRTUALTABLE */
54606
54607 #ifndef SQLITE_OMIT_VIRTUALTABLE
54608 /* Opcode: VColumn P1 P2 P3 * *
54609 **
@@ -55569,11 +56094,11 @@
55569 **
55570 ** This file contains code use to implement an in-memory rollback journal.
55571 ** The in-memory rollback journal is used to journal transactions for
55572 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
55573 **
55574 ** @(#) $Id: memjournal.c,v 1.11 2009/04/05 12:22:09 drh Exp $
55575 */
55576
55577 /* Forward references to internal structures */
55578 typedef struct MemJournal MemJournal;
55579 typedef struct FilePoint FilePoint;
@@ -55683,11 +56208,11 @@
55683 u8 *zWrite = (u8 *)zBuf;
55684
55685 /* An in-memory journal file should only ever be appended to. Random
55686 ** access writes are not required by sqlite.
55687 */
55688 assert(iOfst==p->endpoint.iOffset);
55689 UNUSED_PARAMETER(iOfst);
55690
55691 while( nWrite>0 ){
55692 FileChunk *pChunk = p->endpoint.pChunk;
55693 int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
@@ -55969,11 +56494,11 @@
55969 **
55970 ** This file contains routines used for walking the parser tree and
55971 ** resolve all identifiers by associating them with a particular
55972 ** table and column.
55973 **
55974 ** $Id: resolve.c,v 1.20 2009/03/05 04:23:47 shane Exp $
55975 */
55976
55977 /*
55978 ** Turn the pExpr expression into an alias for the iCol-th column of the
55979 ** result set in pEList.
@@ -56200,11 +56725,15 @@
56200 pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
56201 pExpr->pTab = pTab;
56202 if( iCol>=0 ){
56203 testcase( iCol==31 );
56204 testcase( iCol==32 );
56205 *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0);
 
 
 
 
56206 }
56207 break;
56208 }
56209 }
56210 }
@@ -56271,11 +56800,11 @@
56271 ** pExpr.
56272 **
56273 ** Because no reference was made to outer contexts, the pNC->nRef
56274 ** fields are not changed in any context.
56275 */
56276 if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
56277 sqlite3DbFree(db, zCol);
56278 pExpr->op = TK_STRING;
56279 pExpr->pTab = 0;
56280 return 0;
56281 }
@@ -57139,11 +57668,11 @@
57139 **
57140 *************************************************************************
57141 ** This file contains routines used for analyzing expressions and
57142 ** for generating VDBE code that evaluates expressions in SQLite.
57143 **
57144 ** $Id: expr.c,v 1.426 2009/04/08 13:51:51 drh Exp $
57145 */
57146
57147 /*
57148 ** Return the 'affinity' of the expression pExpr if any.
57149 **
@@ -57533,25 +58062,22 @@
57533 pNew->span.z = (u8*)"";
57534 if( pToken ){
57535 int c;
57536 assert( pToken->dyn==0 );
57537 pNew->span = *pToken;
57538
57539 /* The pToken->z value is read-only. But the new expression
57540 ** node created here might be passed to sqlite3DequoteExpr() which
57541 ** will attempt to modify pNew->token.z. Hence, if the token
57542 ** is quoted, make a copy now so that DequoteExpr() will change
57543 ** the copy rather than the original text.
57544 */
57545 if( pToken->n>=2
57546 && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
57547 sqlite3TokenCopy(db, &pNew->token, pToken);
 
 
 
 
 
57548 }else{
57549 pNew->token = *pToken;
57550 pNew->flags |= EP_Dequoted;
57551 VVA_ONLY( pNew->vvaFlags |= EVVA_ReadOnlyToken; )
57552 }
 
57553 }else if( pLeft ){
57554 if( pRight ){
57555 if( pRight->span.dyn==0 && pLeft->span.dyn==0 ){
57556 sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
57557 }
@@ -57784,22 +58310,10 @@
57784 if( p==0 ) return;
57785 sqlite3ExprClear(db, p);
57786 sqlite3DbFree(db, p);
57787 }
57788
57789 /*
57790 ** The Expr.token field might be a string literal that is quoted.
57791 ** If so, remove the quotation marks.
57792 */
57793 SQLITE_PRIVATE void sqlite3DequoteExpr(Expr *p){
57794 if( !ExprHasAnyProperty(p, EP_Dequoted) ){
57795 ExprSetProperty(p, EP_Dequoted);
57796 assert( (p->vvaFlags & EVVA_ReadOnlyToken)==0 );
57797 sqlite3Dequote((char*)p->token.z);
57798 }
57799 }
57800
57801 /*
57802 ** Return the number of bytes allocated for the expression structure
57803 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
57804 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
57805 */
@@ -58589,11 +59103,11 @@
58589 int isRowid
58590 ){
58591 int testAddr = 0; /* One-time test address */
58592 Vdbe *v = sqlite3GetVdbe(pParse);
58593 if( v==0 ) return;
58594
58595
58596 /* This code must be run in its entirety every time it is encountered
58597 ** if any of the following is true:
58598 **
58599 ** * The right-hand side is a correlated subquery
@@ -58696,15 +59210,11 @@
58696 sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
58697 testAddr = 0;
58698 }
58699
58700 /* Evaluate the expression and insert it into the temp table */
58701 pParse->disableColCache++;
58702 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
58703 assert( pParse->disableColCache>0 );
58704 pParse->disableColCache--;
58705
58706 if( isRowid ){
58707 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, sqlite3VdbeCurrentAddr(v)+2);
58708 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
58709 }else{
58710 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
@@ -58725,11 +59235,11 @@
58725 case TK_SELECT: {
58726 /* This has to be a scalar SELECT. Generate code to put the
58727 ** value of this select in a memory cell and record the number
58728 ** of the memory cell in iColumn.
58729 */
58730 static const Token one = { (u8*)"1", 0, 1 };
58731 Select *pSel;
58732 SelectDest dest;
58733
58734 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
58735 pSel = pExpr->x.pSelect;
@@ -58754,10 +59264,11 @@
58754 }
58755
58756 if( testAddr ){
58757 sqlite3VdbeJumpHere(v, testAddr-1);
58758 }
 
58759
58760 return;
58761 }
58762 #endif /* SQLITE_OMIT_SUBQUERY */
58763
@@ -58831,10 +59342,124 @@
58831 codeReal(v, z, n, negFlag, iMem);
58832 }
58833 }
58834 }
58835
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58836
58837 /*
58838 ** Generate code that will extract the iColumn-th column from
58839 ** table pTab and store the column value in a register. An effort
58840 ** is made to store the column value in register iReg, but this is
@@ -58859,24 +59484,25 @@
58859 ){
58860 Vdbe *v = pParse->pVdbe;
58861 int i;
58862 struct yColCache *p;
58863
58864 for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
58865 if( p->iTable==iTable && p->iColumn==iColumn
58866 && (!p->affChange || allowAffChng) ){
58867 #if 0
58868 sqlite3VdbeAddOp0(v, OP_Noop);
58869 VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
58870 #endif
 
 
58871 return p->iReg;
58872 }
58873 }
58874 assert( v!=0 );
58875 if( iColumn<0 ){
58876 int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
58877 sqlite3VdbeAddOp2(v, op, iTable, iReg);
58878 }else if( pTab==0 ){
58879 sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
58880 }else{
58881 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
58882 sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
@@ -58885,41 +59511,25 @@
58885 if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
58886 sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
58887 }
58888 #endif
58889 }
58890 if( pParse->disableColCache==0 ){
58891 i = pParse->iColCache;
58892 p = &pParse->aColCache[i];
58893 p->iTable = iTable;
58894 p->iColumn = iColumn;
58895 p->iReg = iReg;
58896 p->affChange = 0;
58897 i++;
58898 if( i>=ArraySize(pParse->aColCache) ) i = 0;
58899 if( i>pParse->nColCache ) pParse->nColCache = i;
58900 pParse->iColCache = i;
58901 }
58902 return iReg;
58903 }
58904
58905 /*
58906 ** Clear all column cache entries associated with the vdbe
58907 ** cursor with cursor number iTable.
58908 */
58909 SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){
58910 if( iTable<0 ){
58911 pParse->nColCache = 0;
58912 pParse->iColCache = 0;
58913 }else{
58914 int i;
58915 for(i=0; i<pParse->nColCache; i++){
58916 if( pParse->aColCache[i].iTable==iTable ){
58917 testcase( i==pParse->nColCache-1 );
58918 pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
58919 pParse->iColCache = pParse->nColCache;
58920 }
58921 }
58922 }
58923 }
58924
58925 /*
@@ -58927,14 +59537,15 @@
58927 ** registers starting with iStart.
58928 */
58929 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
58930 int iEnd = iStart + iCount - 1;
58931 int i;
58932 for(i=0; i<pParse->nColCache; i++){
58933 int r = pParse->aColCache[i].iReg;
 
58934 if( r>=iStart && r<=iEnd ){
58935 pParse->aColCache[i].affChange = 1;
58936 }
58937 }
58938 }
58939
58940 /*
@@ -58941,16 +59552,17 @@
58941 ** Generate code to move content from registers iFrom...iFrom+nReg-1
58942 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
58943 */
58944 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
58945 int i;
 
58946 if( iFrom==iTo ) return;
58947 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
58948 for(i=0; i<pParse->nColCache; i++){
58949 int x = pParse->aColCache[i].iReg;
58950 if( x>=iFrom && x<iFrom+nReg ){
58951 pParse->aColCache[i].iReg += iTo-iFrom;
58952 }
58953 }
58954 }
58955
58956 /*
@@ -58969,36 +59581,18 @@
58969 ** Return true if any register in the range iFrom..iTo (inclusive)
58970 ** is used as part of the column cache.
58971 */
58972 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
58973 int i;
58974 for(i=0; i<pParse->nColCache; i++){
58975 int r = pParse->aColCache[i].iReg;
 
58976 if( r>=iFrom && r<=iTo ) return 1;
58977 }
58978 return 0;
58979 }
58980
58981 /*
58982 ** There is a value in register iReg.
58983 **
58984 ** We are going to modify the value, so we need to make sure it
58985 ** is not a cached register. If iReg is a cached register,
58986 ** then clear the corresponding cache line.
58987 */
58988 SQLITE_PRIVATE void sqlite3ExprWritableRegister(Parse *pParse, int iReg){
58989 int i;
58990 if( usedAsColumnCache(pParse, iReg, iReg) ){
58991 for(i=0; i<pParse->nColCache; i++){
58992 if( pParse->aColCache[i].iReg==iReg ){
58993 pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
58994 pParse->iColCache = pParse->nColCache;
58995 }
58996 }
58997 }
58998 }
58999
59000 /*
59001 ** If the last instruction coded is an ephemeral copy of any of
59002 ** the registers in the nReg registers beginning with iReg, then
59003 ** convert the last instruction from OP_SCopy to OP_Copy.
59004 */
@@ -59032,10 +59626,11 @@
59032 ** pParse->aAlias[iAlias-1] records the register number where the value
59033 ** of the iAlias-th alias is stored. If zero, that means that the
59034 ** alias has not yet been computed.
59035 */
59036 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
 
59037 sqlite3 *db = pParse->db;
59038 int iReg;
59039 if( pParse->nAliasAlloc<pParse->nAlias ){
59040 pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
59041 sizeof(pParse->aAlias[0])*pParse->nAlias );
@@ -59046,19 +59641,23 @@
59046 pParse->nAliasAlloc = pParse->nAlias;
59047 }
59048 assert( iAlias>0 && iAlias<=pParse->nAlias );
59049 iReg = pParse->aAlias[iAlias-1];
59050 if( iReg==0 ){
59051 if( pParse->disableColCache ){
59052 iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
59053 }else{
59054 iReg = ++pParse->nMem;
59055 sqlite3ExprCode(pParse, pExpr, iReg);
59056 pParse->aAlias[iAlias-1] = iReg;
59057 }
59058 }
59059 return iReg;
 
 
 
 
59060 }
59061
59062 /*
59063 ** Generate code into the current Vdbe to evaluate the given
59064 ** expression. Attempt to store the results in register "target".
@@ -59124,12 +59723,11 @@
59124 case TK_FLOAT: {
59125 codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
59126 break;
59127 }
59128 case TK_STRING: {
59129 sqlite3DequoteExpr(pExpr);
59130 sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
59131 (char*)pExpr->token.z, pExpr->token.n);
59132 break;
59133 }
59134 case TK_NULL: {
59135 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
@@ -59434,13 +60032,12 @@
59434
59435
59436 /* Code the <expr> from "<expr> IN (...)". The temporary table
59437 ** pExpr->iTable contains the values that make up the (...) set.
59438 */
59439 pParse->disableColCache++;
59440 sqlite3ExprCode(pParse, pExpr->pLeft, target);
59441 pParse->disableColCache--;
59442 j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target);
59443 if( eType==IN_INDEX_ROWID ){
59444 j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target);
59445 j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target);
59446 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
@@ -59497,10 +60094,11 @@
59497 sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target);
59498 }
59499 }
59500 sqlite3VdbeJumpHere(v, j2);
59501 sqlite3VdbeJumpHere(v, j5);
 
59502 VdbeComment((v, "end IN expr r%d", target));
59503 break;
59504 }
59505 #endif
59506 /*
@@ -59573,10 +60171,11 @@
59573 struct ExprList_item *aListelem; /* Array of WHEN terms */
59574 Expr opCompare; /* The X==Ei expression */
59575 Expr cacheX; /* Cached expression X */
59576 Expr *pX; /* The X expression */
59577 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
 
59578
59579 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
59580 assert((pExpr->x.pList->nExpr % 2) == 0);
59581 assert(pExpr->x.pList->nExpr > 0);
59582 pEList = pExpr->x.pList;
@@ -59591,12 +60190,12 @@
59591 cacheX.op = TK_REGISTER;
59592 opCompare.op = TK_EQ;
59593 opCompare.pLeft = &cacheX;
59594 pTest = &opCompare;
59595 }
59596 pParse->disableColCache++;
59597 for(i=0; i<nExpr; i=i+2){
 
59598 if( pX ){
59599 assert( pTest!=0 );
59600 opCompare.pRight = aListelem[i].pExpr;
59601 }else{
59602 pTest = aListelem[i].pExpr;
@@ -59606,20 +60205,23 @@
59606 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
59607 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
59608 testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
59609 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
59610 sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
 
59611 sqlite3VdbeResolveLabel(v, nextCase);
59612 }
59613 if( pExpr->pRight ){
 
59614 sqlite3ExprCode(pParse, pExpr->pRight, target);
 
59615 }else{
59616 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
59617 }
 
 
59618 sqlite3VdbeResolveLabel(v, endLabel);
59619 assert( pParse->disableColCache>0 );
59620 pParse->disableColCache--;
59621 break;
59622 }
59623 #ifndef SQLITE_OMIT_TRIGGER
59624 case TK_RAISE: {
59625 if( !pParse->trigStack ){
@@ -59629,11 +60231,10 @@
59629 }
59630 if( pExpr->affinity!=OE_Ignore ){
59631 assert( pExpr->affinity==OE_Rollback ||
59632 pExpr->affinity == OE_Abort ||
59633 pExpr->affinity == OE_Fail );
59634 sqlite3DequoteExpr(pExpr);
59635 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->affinity, 0,
59636 (char*)pExpr->token.z, pExpr->token.n);
59637 } else {
59638 assert( pExpr->affinity == OE_Ignore );
59639 sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
@@ -59890,27 +60491,21 @@
59890 op = pExpr->op;
59891 switch( op ){
59892 case TK_AND: {
59893 int d2 = sqlite3VdbeMakeLabel(v);
59894 testcase( jumpIfNull==0 );
59895 testcase( pParse->disableColCache==0 );
59896 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
59897 pParse->disableColCache++;
59898 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
59899 assert( pParse->disableColCache>0 );
59900 pParse->disableColCache--;
59901 sqlite3VdbeResolveLabel(v, d2);
 
59902 break;
59903 }
59904 case TK_OR: {
59905 testcase( jumpIfNull==0 );
59906 testcase( pParse->disableColCache==0 );
59907 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
59908 pParse->disableColCache++;
59909 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
59910 assert( pParse->disableColCache>0 );
59911 pParse->disableColCache--;
59912 break;
59913 }
59914 case TK_NOT: {
59915 testcase( jumpIfNull==0 );
59916 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
@@ -60050,28 +60645,22 @@
60050 assert( pExpr->op!=TK_GE || op==OP_Lt );
60051
60052 switch( pExpr->op ){
60053 case TK_AND: {
60054 testcase( jumpIfNull==0 );
60055 testcase( pParse->disableColCache==0 );
60056 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
60057 pParse->disableColCache++;
60058 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
60059 assert( pParse->disableColCache>0 );
60060 pParse->disableColCache--;
60061 break;
60062 }
60063 case TK_OR: {
60064 int d2 = sqlite3VdbeMakeLabel(v);
60065 testcase( jumpIfNull==0 );
60066 testcase( pParse->disableColCache==0 );
60067 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
60068 pParse->disableColCache++;
60069 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
60070 assert( pParse->disableColCache>0 );
60071 pParse->disableColCache--;
60072 sqlite3VdbeResolveLabel(v, d2);
 
60073 break;
60074 }
60075 case TK_NOT: {
60076 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
60077 break;
@@ -60403,21 +60992,37 @@
60403 }
60404 }
60405 }
60406
60407 /*
60408 ** Allocate or deallocate temporary use registers during code generation.
60409 */
60410 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
60411 if( pParse->nTempReg==0 ){
60412 return ++pParse->nMem;
60413 }
60414 return pParse->aTempReg[--pParse->nTempReg];
60415 }
 
 
 
 
 
 
 
 
 
60416 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
60417 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
60418 sqlite3ExprWritableRegister(pParse, iReg);
 
 
 
 
 
 
 
60419 pParse->aTempReg[pParse->nTempReg++] = iReg;
60420 }
60421 }
60422
60423 /*
@@ -60457,11 +61062,11 @@
60457 **
60458 *************************************************************************
60459 ** This file contains C code routines that used to generate VDBE code
60460 ** that implements the ALTER TABLE command.
60461 **
60462 ** $Id: alter.c,v 1.55 2009/03/24 15:08:10 drh Exp $
60463 */
60464
60465 /*
60466 ** The code in this file only exists if we are not omitting the
60467 ** ALTER TABLE logic from the build.
@@ -60669,11 +61274,11 @@
60669 #ifndef SQLITE_OMIT_TRIGGER
60670 Trigger *pTrig;
60671 #endif
60672
60673 v = sqlite3GetVdbe(pParse);
60674 if( !v ) return;
60675 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
60676 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
60677 assert( iDb>=0 );
60678
60679 #ifndef SQLITE_OMIT_TRIGGER
@@ -60723,11 +61328,11 @@
60723 #ifndef SQLITE_OMIT_TRIGGER
60724 char *zWhere = 0; /* Where clause to locate temp triggers */
60725 #endif
60726 int isVirtualRename = 0; /* True if this is a v-table with an xRename() */
60727
60728 if( db->mallocFailed ) goto exit_rename_table;
60729 assert( pSrc->nSrc==1 );
60730 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
60731
60732 pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
60733 if( !pTab ) goto exit_rename_table;
@@ -60956,11 +61561,11 @@
60956
60957 /* Modify the CREATE TABLE statement. */
60958 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
60959 if( zCol ){
60960 char *zEnd = &zCol[pColDef->n-1];
60961 while( (zEnd>zCol && *zEnd==';') || sqlite3Isspace(*zEnd) ){
60962 *zEnd-- = '\0';
60963 }
60964 sqlite3NestedParse(pParse,
60965 "UPDATE \"%w\".%s SET "
60966 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
@@ -61087,11 +61692,11 @@
61087 ** May you share freely, never taking more than you give.
61088 **
61089 *************************************************************************
61090 ** This file contains code associated with the ANALYZE command.
61091 **
61092 ** @(#) $Id: analyze.c,v 1.51 2009/02/28 10:47:42 danielk1977 Exp $
61093 */
61094 #ifndef SQLITE_OMIT_ANALYZE
61095
61096 /*
61097 ** This routine generates code that opens the sqlite_stat1 table on cursor
@@ -61175,11 +61780,11 @@
61175 int endOfLoop; /* The end of the loop */
61176 int addr; /* The address of an instruction */
61177 int iDb; /* Index of database containing pTab */
61178
61179 v = sqlite3GetVdbe(pParse);
61180 if( v==0 || pTab==0 || pTab->pIndex==0 ){
61181 /* Do no analysis for tables that have no indices */
61182 return;
61183 }
61184 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
61185 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
@@ -61375,17 +61980,18 @@
61375 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
61376 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
61377 return;
61378 }
61379
 
61380 if( pName1==0 ){
61381 /* Form 1: Analyze everything */
61382 for(i=0; i<db->nDb; i++){
61383 if( i==1 ) continue; /* Do not analyze the TEMP database */
61384 analyzeDatabase(pParse, i);
61385 }
61386 }else if( pName2==0 || pName2->n==0 ){
61387 /* Form 2: Analyze the database or table named */
61388 iDb = sqlite3FindDb(db, pName1);
61389 if( iDb>=0 ){
61390 analyzeDatabase(pParse, iDb);
61391 }else{
@@ -61520,11 +62126,11 @@
61520 ** May you share freely, never taking more than you give.
61521 **
61522 *************************************************************************
61523 ** This file contains code used to implement the ATTACH and DETACH commands.
61524 **
61525 ** $Id: attach.c,v 1.84 2009/04/08 13:51:51 drh Exp $
61526 */
61527
61528 #ifndef SQLITE_OMIT_ATTACH
61529 /*
61530 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
@@ -61582,11 +62188,10 @@
61582 sqlite3 *db = sqlite3_context_db_handle(context);
61583 const char *zName;
61584 const char *zFile;
61585 Db *aNew;
61586 char *zErrDyn = 0;
61587 char zErr[128];
61588
61589 UNUSED_PARAMETER(NotUsed);
61590
61591 zFile = (const char *)sqlite3_value_text(argv[0]);
61592 zName = (const char *)sqlite3_value_text(argv[1]);
@@ -61598,26 +62203,24 @@
61598 ** * Too many attached databases,
61599 ** * Transaction currently open
61600 ** * Specified database name already being used.
61601 */
61602 if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
61603 sqlite3_snprintf(
61604 sizeof(zErr), zErr, "too many attached databases - max %d",
61605 db->aLimit[SQLITE_LIMIT_ATTACHED]
61606 );
61607 goto attach_error;
61608 }
61609 if( !db->autoCommit ){
61610 sqlite3_snprintf(sizeof(zErr), zErr,
61611 "cannot ATTACH database within transaction");
61612 goto attach_error;
61613 }
61614 for(i=0; i<db->nDb; i++){
61615 char *z = db->aDb[i].zName;
61616 if( z && zName && sqlite3StrICmp(z, zName)==0 ){
61617 sqlite3_snprintf(sizeof(zErr), zErr,
61618 "database %s is already in use", zName);
61619 goto attach_error;
61620 }
61621 }
61622
61623 /* Allocate the new entry in the db->aDb[] array and initialise the schema
@@ -61630,29 +62233,33 @@
61630 }else{
61631 aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
61632 if( aNew==0 ) return;
61633 }
61634 db->aDb = aNew;
61635 aNew = &db->aDb[db->nDb++];
61636 memset(aNew, 0, sizeof(*aNew));
61637
61638 /* Open the database file. If the btree is successfully opened, use
61639 ** it to obtain the database schema. At this point the schema may
61640 ** or may not be initialised.
61641 */
61642 rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
61643 db->openFlags | SQLITE_OPEN_MAIN_DB,
61644 &aNew->pBt);
61645 if( rc==SQLITE_OK ){
 
 
 
 
61646 Pager *pPager;
61647 aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
61648 if( !aNew->pSchema ){
61649 rc = SQLITE_NOMEM;
61650 }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
61651 sqlite3_snprintf(sizeof(zErr), zErr,
61652 "attached databases must use the same text encoding as main database");
61653 goto attach_error;
61654 }
61655 pPager = sqlite3BtreePager(aNew->pBt);
61656 sqlite3PagerLockingMode(pPager, db->dfltLockMode);
61657 sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
61658 }
@@ -61711,13 +62318,14 @@
61711 }
61712 sqlite3ResetInternalSchema(db, 0);
61713 db->nDb = iDb;
61714 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
61715 db->mallocFailed = 1;
61716 sqlite3_snprintf(sizeof(zErr),zErr, "out of memory");
61717 }else{
61718 sqlite3_snprintf(sizeof(zErr),zErr, "unable to open database: %s", zFile);
 
61719 }
61720 goto attach_error;
61721 }
61722
61723 return;
@@ -61725,13 +62333,10 @@
61725 attach_error:
61726 /* Return an error if we get here */
61727 if( zErrDyn ){
61728 sqlite3_result_error(context, zErrDyn, -1);
61729 sqlite3DbFree(db, zErrDyn);
61730 }else{
61731 zErr[sizeof(zErr)-1] = 0;
61732 sqlite3_result_error(context, zErr, -1);
61733 }
61734 if( rc ) sqlite3_result_error_code(context, rc);
61735 }
61736
61737 /*
@@ -61919,11 +62524,11 @@
61919 const char *zType, /* "view", "trigger", or "index" */
61920 const Token *pName /* Name of the view, trigger, or index */
61921 ){
61922 sqlite3 *db;
61923
61924 if( iDb<0 || iDb==1 ) return 0;
61925 db = pParse->db;
61926 assert( db->nDb>iDb );
61927 pFix->pParse = pParse;
61928 pFix->zDb = db->aDb[iDb].zName;
61929 pFix->zType = zType;
@@ -61951,11 +62556,11 @@
61951 ){
61952 int i;
61953 const char *zDb;
61954 struct SrcList_item *pItem;
61955
61956 if( pList==0 ) return 0;
61957 zDb = pFix->zDb;
61958 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
61959 if( pItem->zDatabase==0 ){
61960 pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
61961 }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
@@ -62064,11 +62669,11 @@
62064 ** This file contains code used to implement the sqlite3_set_authorizer()
62065 ** API. This facility is an optional feature of the library. Embedded
62066 ** systems that do not need this facility may omit it by recompiling
62067 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
62068 **
62069 ** $Id: auth.c,v 1.29 2007/09/18 15:55:07 drh Exp $
62070 */
62071
62072 /*
62073 ** All of the code in this file may be omitted by defining a single
62074 ** macro.
@@ -62135,14 +62740,12 @@
62135
62136 /*
62137 ** Write an error message into pParse->zErrMsg that explains that the
62138 ** user-supplied authorization function returned an illegal value.
62139 */
62140 static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
62141 sqlite3ErrorMsg(pParse, "illegal return value (%d) from the "
62142 "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
62143 "or SQLITE_DENY", rc);
62144 pParse->rc = SQLITE_ERROR;
62145 }
62146
62147 /*
62148 ** The pExpr should be a TK_COLUMN expression. The table referred to
@@ -62167,30 +62770,34 @@
62167 const char *zDBase; /* Name of database being accessed */
62168 TriggerStack *pStack; /* The stack of current triggers */
62169 int iDb; /* The index of the database the expression refers to */
62170
62171 if( db->xAuth==0 ) return;
62172 if( pExpr->op!=TK_COLUMN ) return;
62173 iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
62174 if( iDb<0 ){
62175 /* An attempt to read a column out of a subquery or other
62176 ** temporary table. */
62177 return;
62178 }
62179 for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
62180 if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
62181 }
62182 if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
 
62183 pTab = pTabList->a[iSrc].pTab;
62184 }else if( (pStack = pParse->trigStack)!=0 ){
62185 /* This must be an attempt to read the NEW or OLD pseudo-tables
62186 ** of a trigger.
62187 */
62188 assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
62189 pTab = pStack->pTab;
62190 }
62191 if( pTab==0 ) return;
 
 
 
62192 if( pExpr->iColumn>=0 ){
62193 assert( pExpr->iColumn<pTab->nCol );
62194 zCol = pTab->aCol[pExpr->iColumn].zName;
62195 }else if( pTab->iPKey>=0 ){
62196 assert( pTab->iPKey<pTab->nCol );
@@ -62211,11 +62818,11 @@
62211 }else{
62212 sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
62213 }
62214 pParse->rc = SQLITE_AUTH;
62215 }else if( rc!=SQLITE_OK ){
62216 sqliteAuthBadReturnCode(pParse, rc);
62217 }
62218 }
62219
62220 /*
62221 ** Do an authorization check using the code and arguments given. Return
@@ -62247,11 +62854,11 @@
62247 if( rc==SQLITE_DENY ){
62248 sqlite3ErrorMsg(pParse, "not authorized");
62249 pParse->rc = SQLITE_AUTH;
62250 }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
62251 rc = SQLITE_DENY;
62252 sqliteAuthBadReturnCode(pParse, rc);
62253 }
62254 return rc;
62255 }
62256
62257 /*
@@ -62262,15 +62869,14 @@
62262 SQLITE_PRIVATE void sqlite3AuthContextPush(
62263 Parse *pParse,
62264 AuthContext *pContext,
62265 const char *zContext
62266 ){
 
62267 pContext->pParse = pParse;
62268 if( pParse ){
62269 pContext->zAuthContext = pParse->zAuthContext;
62270 pParse->zAuthContext = zContext;
62271 }
62272 }
62273
62274 /*
62275 ** Pop an authorization context that was previously pushed
62276 ** by sqlite3AuthContextPush
@@ -62308,11 +62914,11 @@
62308 ** creating ID lists
62309 ** BEGIN TRANSACTION
62310 ** COMMIT
62311 ** ROLLBACK
62312 **
62313 ** $Id: build.c,v 1.528 2009/04/08 13:51:51 drh Exp $
62314 */
62315
62316 /*
62317 ** This routine is called when a new SQL statement is beginning to
62318 ** be parsed. Initialize the pParse structure as needed.
@@ -62443,11 +63049,13 @@
62443 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
62444 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
62445 if( (mask & pParse->cookieMask)==0 ) continue;
62446 sqlite3VdbeUsesBtree(v, iDb);
62447 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
62448 sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
 
 
62449 }
62450 #ifndef SQLITE_OMIT_VIRTUALTABLE
62451 {
62452 int i;
62453 for(i=0; i<pParse->nVtabLock; i++){
@@ -62473,11 +63081,11 @@
62473 if( v && pParse->nErr==0 && !db->mallocFailed ){
62474 #ifdef SQLITE_DEBUG
62475 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
62476 sqlite3VdbeTrace(v, trace);
62477 #endif
62478 assert( pParse->disableColCache==0 ); /* Disables and re-enables match */
62479 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
62480 pParse->nTab, pParse->explain);
62481 pParse->rc = SQLITE_DONE;
62482 pParse->colNamesSet = 0;
62483 }else if( pParse->rc==SQLITE_OK ){
@@ -62544,11 +63152,11 @@
62544 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
62545 Table *p = 0;
62546 int i;
62547 int nName;
62548 assert( zName!=0 );
62549 nName = sqlite3Strlen(db, zName) + 1;
62550 for(i=OMIT_TEMPDB; i<db->nDb; i++){
62551 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
62552 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
62553 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
62554 if( p ) break;
@@ -62606,11 +63214,11 @@
62606 ** using the ATTACH command.
62607 */
62608 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
62609 Index *p = 0;
62610 int i;
62611 int nName = sqlite3Strlen(db, zName)+1;
62612 for(i=OMIT_TEMPDB; i<db->nDb; i++){
62613 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
62614 Schema *pSchema = db->aDb[j].pSchema;
62615 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
62616 assert( pSchema || (j==1 && !db->aDb[1].pBt) );
@@ -62642,11 +63250,11 @@
62642 static void sqlite3DeleteIndex(Index *p){
62643 Index *pOld;
62644 const char *zName = p->zName;
62645
62646 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
62647 sqlite3Strlen30(zName)+1, 0);
62648 assert( pOld==0 || pOld==p );
62649 freeIndex(p);
62650 }
62651
62652 /*
@@ -62658,12 +63266,12 @@
62658 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
62659 Index *pIndex;
62660 int len;
62661 Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
62662
62663 len = sqlite3Strlen(db, zIdxName);
62664 pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
62665 if( pIndex ){
62666 if( pIndex->pTable->pIndex==pIndex ){
62667 pIndex->pTable->pIndex = pIndex->pNext;
62668 }else{
62669 Index *p;
@@ -62772,12 +63380,11 @@
62772 /*
62773 ** Remove the memory data structures associated with the given
62774 ** Table. No changes are made to disk by this routine.
62775 **
62776 ** This routine just deletes the data structure. It does not unlink
62777 ** the table data structure from the hash table. Nor does it remove
62778 ** foreign keys from the sqlite.aFKey hash table. But it does destroy
62779 ** memory structures of the indices and foreign keys associated with
62780 ** the table.
62781 */
62782 SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
62783 Index *pIndex, *pNext;
@@ -62801,17 +63408,13 @@
62801 assert( pIndex->pSchema==pTable->pSchema );
62802 sqlite3DeleteIndex(pIndex);
62803 }
62804
62805 #ifndef SQLITE_OMIT_FOREIGN_KEY
62806 /* Delete all foreign keys associated with this table. The keys
62807 ** should have already been unlinked from the pSchema->aFKey hash table
62808 */
62809 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
62810 pNextFKey = pFKey->pNextFrom;
62811 assert( sqlite3HashFind(&pTable->pSchema->aFKey,
62812 pFKey->zTo, sqlite3Strlen30(pFKey->zTo)+1)!=pFKey );
62813 sqlite3DbFree(db, pFKey);
62814 }
62815 #endif
62816
62817 /* Delete the Table structure itself.
@@ -62831,54 +63434,40 @@
62831 ** Unlink the given table from the hash tables and the delete the
62832 ** table structure with all its indices and foreign keys.
62833 */
62834 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
62835 Table *p;
62836 FKey *pF1, *pF2;
62837 Db *pDb;
62838
62839 assert( db!=0 );
62840 assert( iDb>=0 && iDb<db->nDb );
62841 assert( zTabName && zTabName[0] );
62842 pDb = &db->aDb[iDb];
62843 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
62844 sqlite3Strlen30(zTabName)+1,0);
62845 if( p ){
62846 #ifndef SQLITE_OMIT_FOREIGN_KEY
62847 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
62848 int nTo = sqlite3Strlen30(pF1->zTo) + 1;
62849 pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
62850 if( pF2==pF1 ){
62851 sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
62852 }else{
62853 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
62854 if( pF2 ){
62855 pF2->pNextTo = pF1->pNextTo;
62856 }
62857 }
62858 }
62859 #endif
62860 sqlite3DeleteTable(p);
62861 }
62862 db->flags |= SQLITE_InternChanges;
62863 }
62864
62865 /*
62866 ** Given a token, return a string that consists of the text of that
62867 ** token with any quotations removed. Space to hold the returned string
62868 ** is obtained from sqliteMalloc() and must be freed by the calling
62869 ** function.
 
 
 
62870 **
62871 ** Tokens are often just pointers into the original SQL text and so
62872 ** are not \000 terminated and are not persistent. The returned string
62873 ** is \000 terminated and is persistent.
62874 */
62875 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
62876 char *zName;
62877 if( pName ){
62878 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
62879 sqlite3Dequote(zName);
62880 }else{
62881 zName = 0;
62882 }
62883 return zName;
62884 }
@@ -63563,11 +64152,11 @@
63563 pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
63564 if( !initbusy && (!pColl || !pColl->xCmp) ){
63565 pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
63566 if( !pColl ){
63567 if( nName<0 ){
63568 nName = sqlite3Strlen(db, zName);
63569 }
63570 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
63571 pColl = 0;
63572 }
63573 }
@@ -63968,30 +64557,18 @@
63968
63969 /* Add the table to the in-memory representation of the database.
63970 */
63971 if( db->init.busy && pParse->nErr==0 ){
63972 Table *pOld;
63973 FKey *pFKey;
63974 Schema *pSchema = p->pSchema;
63975 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
63976 sqlite3Strlen30(p->zName)+1,p);
63977 if( pOld ){
63978 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
63979 db->mallocFailed = 1;
63980 return;
63981 }
63982 #ifndef SQLITE_OMIT_FOREIGN_KEY
63983 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
63984 void *data;
63985 int nTo = sqlite3Strlen30(pFKey->zTo) + 1;
63986 pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
63987 data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
63988 if( data==(void *)pFKey ){
63989 db->mallocFailed = 1;
63990 }
63991 }
63992 #endif
63993 pParse->pNewTable = 0;
63994 db->nTable++;
63995 db->flags |= SQLITE_InternChanges;
63996
63997 #ifndef SQLITE_OMIT_ALTERTABLE
@@ -64494,13 +65071,11 @@
64494 ** pTo table that the foreign key points to. flags contains all
64495 ** information about the conflict resolution algorithms specified
64496 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
64497 **
64498 ** An FKey structure is created and added to the table currently
64499 ** under construction in the pParse->pNewTable field. The new FKey
64500 ** is not linked into db->aFKey at this point - that does not happen
64501 ** until sqlite3EndTable().
64502 **
64503 ** The foreign key is set for IMMEDIATE processing. A subsequent call
64504 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
64505 */
64506 SQLITE_PRIVATE void sqlite3CreateForeignKey(
@@ -64537,11 +65112,11 @@
64537 "columns in the referenced table");
64538 goto fk_end;
64539 }else{
64540 nCol = pFromCol->nExpr;
64541 }
64542 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
64543 if( pToCol ){
64544 for(i=0; i<pToCol->nExpr; i++){
64545 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
64546 }
64547 }
@@ -64549,18 +65124,16 @@
64549 if( pFKey==0 ){
64550 goto fk_end;
64551 }
64552 pFKey->pFrom = p;
64553 pFKey->pNextFrom = p->pFKey;
64554 z = (char*)&pFKey[1];
64555 pFKey->aCol = (struct sColMap*)z;
64556 z += sizeof(struct sColMap)*nCol;
64557 pFKey->zTo = z;
64558 memcpy(z, pTo->z, pTo->n);
64559 z[pTo->n] = 0;
 
64560 z += pTo->n+1;
64561 pFKey->pNextTo = 0;
64562 pFKey->nCol = nCol;
64563 if( pFromCol==0 ){
64564 pFKey->aCol[0].iFrom = p->nCol-1;
64565 }else{
64566 for(i=0; i<nCol; i++){
@@ -64673,23 +65246,29 @@
64673 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
64674 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
64675 regRecord = sqlite3GetTempReg(pParse);
64676 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
64677 if( pIndex->onError!=OE_None ){
64678 int j1, j2;
64679 int regRowid;
 
64680
64681 regRowid = regIdxKey + pIndex->nColumn;
64682 j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn);
64683 j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx,
64684 0, regRowid, SQLITE_INT_TO_PTR(regRecord), P4_INT32);
 
 
 
 
 
 
64685 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
64686 "indexed columns are not unique", P4_STATIC);
64687 sqlite3VdbeJumpHere(v, j1);
64688 sqlite3VdbeJumpHere(v, j2);
64689 }
64690 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
 
64691 sqlite3ReleaseTempReg(pParse, regRecord);
64692 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
64693 sqlite3VdbeJumpHere(v, addr1);
64694 sqlite3VdbeAddOp1(v, OP_Close, iTab);
64695 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
@@ -64868,10 +65447,11 @@
64868 ** So create a fake list to simulate this.
64869 */
64870 if( pList==0 ){
64871 nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
64872 nullId.n = sqlite3Strlen30((char*)nullId.z);
 
64873 pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
64874 if( pList==0 ) goto exit_create_index;
64875 pList->a[0].sortOrder = (u8)sortOrder;
64876 }
64877
@@ -65024,11 +65604,11 @@
65024 ** in-memory database structures.
65025 */
65026 if( db->init.busy ){
65027 Index *p;
65028 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
65029 pIndex->zName, sqlite3Strlen30(pIndex->zName)+1,
65030 pIndex);
65031 if( p ){
65032 assert( p==pIndex ); /* Malloc must have failed */
65033 db->mallocFailed = 1;
65034 goto exit_create_index;
@@ -65981,11 +66561,11 @@
65981 *************************************************************************
65982 **
65983 ** This file contains functions used to access the internal hash tables
65984 ** of user defined functions and collation sequences.
65985 **
65986 ** $Id: callback.c,v 1.37 2009/03/24 15:08:10 drh Exp $
65987 */
65988
65989
65990 /*
65991 ** Invoke the 'collation needed' callback to request a collation sequence
@@ -65992,11 +66572,11 @@
65992 ** in the database text encoding of name zName, length nName.
65993 ** If the collation sequence
65994 */
65995 static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
65996 assert( !db->xCollNeeded || !db->xCollNeeded16 );
65997 if( nName<0 ) nName = sqlite3Strlen(db, zName);
65998 if( db->xCollNeeded ){
65999 char *zExternal = sqlite3DbStrNDup(db, zName, nName);
66000 if( !zExternal ) return;
66001 db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
66002 sqlite3DbFree(db, zExternal);
@@ -66125,11 +66705,11 @@
66125 const char *zName,
66126 int nName,
66127 int create
66128 ){
66129 CollSeq *pColl;
66130 if( nName<0 ) nName = sqlite3Strlen(db, zName);
66131 pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
66132
66133 if( 0==pColl && create ){
66134 pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
66135 if( pColl ){
@@ -66380,18 +66960,17 @@
66380 HashElem *pElem;
66381 Schema *pSchema = (Schema *)p;
66382
66383 temp1 = pSchema->tblHash;
66384 temp2 = pSchema->trigHash;
66385 sqlite3HashInit(&pSchema->trigHash, 0);
66386 sqlite3HashClear(&pSchema->aFKey);
66387 sqlite3HashClear(&pSchema->idxHash);
66388 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
66389 sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
66390 }
66391 sqlite3HashClear(&temp2);
66392 sqlite3HashInit(&pSchema->tblHash, 0);
66393 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
66394 Table *pTab = sqliteHashData(pElem);
66395 assert( pTab->dbMem==0 );
66396 sqlite3DeleteTable(pTab);
66397 }
@@ -66412,14 +66991,13 @@
66412 p = (Schema *)sqlite3MallocZero(sizeof(Schema));
66413 }
66414 if( !p ){
66415 db->mallocFailed = 1;
66416 }else if ( 0==p->file_format ){
66417 sqlite3HashInit(&p->tblHash, 0);
66418 sqlite3HashInit(&p->idxHash, 0);
66419 sqlite3HashInit(&p->trigHash, 0);
66420 sqlite3HashInit(&p->aFKey, 1);
66421 p->enc = SQLITE_UTF8;
66422 }
66423 return p;
66424 }
66425
@@ -66437,11 +67015,11 @@
66437 **
66438 *************************************************************************
66439 ** This file contains C code routines that are called by the parser
66440 ** in order to generate code for DELETE FROM statements.
66441 **
66442 ** $Id: delete.c,v 1.198 2009/03/05 03:48:07 shane Exp $
66443 */
66444
66445 /*
66446 ** Look up every table that is named in pSrc. If any table is not found,
66447 ** add an error message to pParse->zErrMsg and return NULL. If all tables
@@ -66486,30 +67064,10 @@
66486 }
66487 #endif
66488 return 0;
66489 }
66490
66491 /*
66492 ** Generate code that will open a table for reading.
66493 */
66494 SQLITE_PRIVATE void sqlite3OpenTable(
66495 Parse *p, /* Generate code into this VDBE */
66496 int iCur, /* The cursor number of the table */
66497 int iDb, /* The database index in sqlite3.aDb[] */
66498 Table *pTab, /* The table to be opened */
66499 int opcode /* OP_OpenRead or OP_OpenWrite */
66500 ){
66501 Vdbe *v;
66502 if( IsVirtual(pTab) ) return;
66503 v = sqlite3GetVdbe(p);
66504 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
66505 sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
66506 sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
66507 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
66508 VdbeComment((v, "%s", pTab->zName));
66509 }
66510
66511
66512 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
66513 /*
66514 ** Evaluate a view and store its result in an ephemeral table. The
66515 ** pWhere argument is an optional WHERE clause that restricts the
@@ -66531,10 +67089,11 @@
66531 Token viewName;
66532
66533 pWhere = sqlite3ExprDup(db, pWhere, 0);
66534 viewName.z = (u8*)pView->zName;
66535 viewName.n = (unsigned int)sqlite3Strlen30((const char*)viewName.z);
 
66536 pFrom = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, &viewName, pDup, 0,0);
66537 pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
66538 }
66539 sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
66540 sqlite3Select(pParse, pDup, &dest);
@@ -66801,14 +67360,12 @@
66801 ** It is easier just to erase the whole table. Note, however, that
66802 ** this means that the row change count will be incorrect.
66803 */
66804 if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) ){
66805 assert( !isView );
66806 sqlite3VdbeAddOp3(v, OP_Clear, pTab->tnum, iDb, memCnt);
66807 if( !pParse->nested ){
66808 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
66809 }
66810 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
66811 assert( pIdx->pSchema==pTab->pSchema );
66812 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
66813 }
66814 }else
@@ -66817,17 +67374,19 @@
66817 ** the table and pick which records to delete.
66818 */
66819 {
66820 int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
66821 int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
 
66822
66823 /* Collect rowids of every row to be deleted.
66824 */
66825 sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
66826 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
66827 WHERE_FILL_ROWSET, iRowSet);
66828 if( pWInfo==0 ) goto delete_from_cleanup;
 
 
66829 if( db->flags & SQLITE_CountRows ){
66830 sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
66831 }
66832 sqlite3WhereEnd(pWInfo);
66833
@@ -67074,11 +67633,11 @@
67074 **
67075 ** There is only one exported symbol in this file - the function
67076 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
67077 ** All other code has file scope.
67078 **
67079 ** $Id: func.c,v 1.231 2009/04/08 23:04:14 drh Exp $
67080 */
67081
67082 /*
67083 ** Return the collating function associated with a function.
67084 */
@@ -68233,16 +68792,18 @@
68233 p = sqlite3_aggregate_context(context, sizeof(*p));
68234 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
68235 p->n++;
68236 }
68237
 
68238 /* The sqlite3_aggregate_count() function is deprecated. But just to make
68239 ** sure it still operates correctly, verify that its count agrees with our
68240 ** internal count when using count(*) and when the total count can be
68241 ** expressed as a 32-bit integer. */
68242 assert( argc==1 || p==0 || p->n>0x7fffffff
68243 || p->n==sqlite3_aggregate_count(context) );
 
68244 }
68245 static void countFinalize(sqlite3_context *context){
68246 CountCtx *p;
68247 p = sqlite3_aggregate_context(context, 0);
68248 sqlite3_result_int64(context, p ? p->n : 0);
@@ -68312,13 +68873,19 @@
68312 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
68313 pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
68314
68315 if( pAccum ){
68316 sqlite3 *db = sqlite3_context_db_handle(context);
 
68317 pAccum->useMalloc = 1;
68318 pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
68319 if( pAccum->nChar ){
 
 
 
 
 
68320 if( argc==2 ){
68321 zSep = (char*)sqlite3_value_text(argv[1]);
68322 nSep = sqlite3_value_bytes(argv[1]);
68323 }else{
68324 zSep = ",";
@@ -68539,12 +69106,32 @@
68539 **
68540 *************************************************************************
68541 ** This file contains C code routines that are called by the parser
68542 ** to handle INSERT statements in SQLite.
68543 **
68544 ** $Id: insert.c,v 1.260 2009/02/28 10:47:42 danielk1977 Exp $
68545 */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68546
68547 /*
68548 ** Set P4 of the most recently inserted opcode to a column affinity
68549 ** string for index pIdx. A column affinity string has one character
68550 ** for each column in the table, according to the affinity of the column:
@@ -68941,11 +69528,11 @@
68941
68942 /* Locate the table into which we will be inserting new information.
68943 */
68944 assert( pTabList->nSrc==1 );
68945 zTab = pTabList->a[0].zName;
68946 if( zTab==0 ) goto insert_cleanup;
68947 pTab = sqlite3SrcListLookup(pParse, pTabList);
68948 if( pTab==0 ){
68949 goto insert_cleanup;
68950 }
68951 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
@@ -69063,11 +69650,12 @@
69063 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
69064 VdbeComment((v, "Jump over SELECT coroutine"));
69065
69066 /* Resolve the expressions in the SELECT statement and execute it. */
69067 rc = sqlite3Select(pParse, pSelect, &dest);
69068 if( rc || pParse->nErr || db->mallocFailed ){
 
69069 goto insert_cleanup;
69070 }
69071 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
69072 sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */
69073 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
@@ -69149,11 +69737,11 @@
69149 }
69150 }
69151 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
69152 sqlite3ErrorMsg(pParse,
69153 "table %S has %d columns but %d values were supplied",
69154 pTabList, 0, pTab->nCol, nColumn);
69155 goto insert_cleanup;
69156 }
69157 if( pColumn!=0 && nColumn!=pColumn->nId ){
69158 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
69159 goto insert_cleanup;
@@ -69287,16 +69875,18 @@
69287 ** not happened yet) so we substitute a rowid of -1
69288 */
69289 regTrigRowid = sqlite3GetTempReg(pParse);
69290 if( keyColumn<0 ){
69291 sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
69292 }else if( useTempTable ){
69293 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regTrigRowid);
69294 }else{
69295 int j1;
69296 assert( pSelect==0 ); /* Otherwise useTempTable is true */
69297 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regTrigRowid);
 
 
 
 
69298 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regTrigRowid);
69299 sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
69300 sqlite3VdbeJumpHere(v, j1);
69301 sqlite3VdbeAddOp1(v, OP_MustBeInt, regTrigRowid);
69302 }
@@ -69366,11 +69956,11 @@
69366 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
69367 }else{
69368 VdbeOp *pOp;
69369 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
69370 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
69371 if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
69372 appendFlag = 1;
69373 pOp->opcode = OP_NewRowid;
69374 pOp->p1 = baseCur;
69375 pOp->p2 = regRowid;
69376 pOp->p3 = regAutoinc;
@@ -69446,31 +70036,18 @@
69446 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
69447 (const char*)pTab->pVtab, P4_VTAB);
69448 }else
69449 #endif
69450 {
69451 sqlite3GenerateConstraintChecks(
69452 pParse,
69453 pTab,
69454 baseCur,
69455 regIns,
69456 aRegIdx,
69457 keyColumn>=0,
69458 0,
69459 onError,
69460 endOfLoop
69461 );
69462 sqlite3CompleteInsertion(
69463 pParse,
69464 pTab,
69465 baseCur,
69466 regIns,
69467 aRegIdx,
69468 0,
69469 (tmask&TRIGGER_AFTER) ? newIdx : -1,
69470 appendFlag
69471 );
69472 }
69473 }
69474
69475 /* Update the count of rows that are inserted
69476 */
@@ -69616,22 +70193,23 @@
69616 int regRowid, /* Index of the range of input registers */
69617 int *aRegIdx, /* Register used by each index. 0 for unused indices */
69618 int rowidChng, /* True if the rowid might collide with existing entry */
69619 int isUpdate, /* True for UPDATE, False for INSERT */
69620 int overrideError, /* Override onError to this if not OE_Default */
69621 int ignoreDest /* Jump to this label on an OE_Ignore resolution */
 
69622 ){
69623 int i;
69624 Vdbe *v;
69625 int nCol;
69626 int onError;
69627 int j1; /* Addresss of jump instruction */
69628 int j2 = 0, j3; /* Addresses of jump instructions */
69629 int regData; /* Register containing first data column */
69630 int iCur;
69631 Index *pIdx;
69632 int seenReplace = 0;
69633 int hasTwoRowids = (isUpdate && rowidChng);
69634
69635 v = sqlite3GetVdbe(pParse);
69636 assert( v!=0 );
69637 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
@@ -69671,11 +70249,12 @@
69671 }
69672 case OE_Ignore: {
69673 sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
69674 break;
69675 }
69676 case OE_Replace: {
 
69677 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
69678 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
69679 sqlite3VdbeJumpHere(v, j1);
69680 break;
69681 }
@@ -69768,15 +70347,17 @@
69768 }
69769 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
69770 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
69771 sqlite3IndexAffinityStr(v, pIdx);
69772 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
69773 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
69774
69775 /* Find out what action to take in case there is an indexing conflict */
69776 onError = pIdx->onError;
69777 if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
 
 
 
69778 if( overrideError!=OE_Default ){
69779 onError = overrideError;
69780 }else if( onError==OE_Default ){
69781 onError = OE_Abort;
69782 }
@@ -69785,65 +70366,64 @@
69785 else if( onError==OE_Fail ) onError = OE_Abort;
69786 }
69787
69788
69789 /* Check to see if the new index entry will be unique */
69790 j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn);
69791 regR = sqlite3GetTempReg(pParse);
69792 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
69793 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
69794 regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]),
69795 P4_INT32);
 
69796
69797 /* Generate code that executes if the new index entry is not unique */
69798 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
69799 || onError==OE_Ignore || onError==OE_Replace );
69800 switch( onError ){
69801 case OE_Rollback:
69802 case OE_Abort:
69803 case OE_Fail: {
69804 int j, n1, n2;
69805 char zErrMsg[200];
69806 sqlite3_snprintf(ArraySize(zErrMsg), zErrMsg,
69807 pIdx->nColumn>1 ? "columns " : "column ");
69808 n1 = sqlite3Strlen30(zErrMsg);
69809 for(j=0; j<pIdx->nColumn && n1<ArraySize(zErrMsg)-30; j++){
 
 
 
69810 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
69811 n2 = sqlite3Strlen30(zCol);
69812 if( j>0 ){
69813 sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], ", ");
69814 n1 += 2;
69815 }
69816 if( n1+n2>ArraySize(zErrMsg)-30 ){
69817 sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "...");
69818 n1 += 3;
69819 break;
69820 }else{
69821 sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1], "%s", zCol);
69822 n1 += n2;
69823 }
69824 }
69825 sqlite3_snprintf(ArraySize(zErrMsg)-n1, &zErrMsg[n1],
69826 pIdx->nColumn>1 ? " are not unique" : " is not unique");
69827 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0);
69828 break;
69829 }
69830 case OE_Ignore: {
69831 assert( seenReplace==0 );
69832 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
69833 break;
69834 }
69835 case OE_Replace: {
 
69836 sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
69837 seenReplace = 1;
69838 break;
69839 }
69840 }
69841 sqlite3VdbeJumpHere(v, j2);
69842 sqlite3VdbeJumpHere(v, j3);
69843 sqlite3ReleaseTempReg(pParse, regR);
69844 }
 
 
 
 
69845 }
69846
69847 /*
69848 ** This routine generates code to finish the INSERT or UPDATE operation
69849 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
@@ -69859,11 +70439,12 @@
69859 int baseCur, /* Index of a read/write cursor pointing at pTab */
69860 int regRowid, /* Range of content */
69861 int *aRegIdx, /* Register used by each index. 0 for unused indices */
69862 int isUpdate, /* True for UPDATE, False for INSERT */
69863 int newIdx, /* Index of NEW table for triggers. -1 if none */
69864 int appendBias /* True if this is likely to be an append */
 
69865 ){
69866 int i;
69867 Vdbe *v;
69868 int nIdx;
69869 Index *pIdx;
@@ -69876,10 +70457,13 @@
69876 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
69877 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
69878 for(i=nIdx-1; i>=0; i--){
69879 if( aRegIdx[i]==0 ) continue;
69880 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
 
 
 
69881 }
69882 regData = regRowid + 1;
69883 regRec = sqlite3GetTempReg(pParse);
69884 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
69885 sqlite3TableAffinityStr(v, pTab);
@@ -69896,10 +70480,13 @@
69896 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
69897 }
69898 if( appendBias ){
69899 pik_flags |= OPFLAG_APPEND;
69900 }
 
 
 
69901 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
69902 if( !pParse->nested ){
69903 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
69904 }
69905 sqlite3VdbeChangeP5(v, pik_flags);
@@ -69933,11 +70520,11 @@
69933 assert( pIdx->pSchema==pTab->pSchema );
69934 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
69935 (char*)pKey, P4_KEYINFO_HANDOFF);
69936 VdbeComment((v, "%s", pIdx->zName));
69937 }
69938 if( pParse->nTab<=baseCur+i ){
69939 pParse->nTab = baseCur+i;
69940 }
69941 return i-1;
69942 }
69943
@@ -69993,11 +70580,11 @@
69993 return 0; /* Different columns indexed */
69994 }
69995 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
69996 return 0; /* Different sort orders */
69997 }
69998 if( pSrc->azColl[i]!=pDest->azColl[i] ){
69999 return 0; /* Different collating sequences */
70000 }
70001 }
70002
70003 /* If no test above fails then the indices must be compatible */
@@ -70224,11 +70811,11 @@
70224 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
70225 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
70226 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
70227 autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
70228 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
70229 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
70230 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
70231 }
70232 assert( pSrcIdx );
70233 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
70234 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
@@ -70283,11 +70870,11 @@
70283 ** Main file for the SQLite library. The routines in this file
70284 ** implement the programmer interface to the library. Routines in
70285 ** other files are for internal use by SQLite and should not be
70286 ** accessed by users of the library.
70287 **
70288 ** $Id: legacy.c,v 1.32 2009/03/19 18:51:07 danielk1977 Exp $
70289 */
70290
70291
70292 /*
70293 ** Execute SQL code. Return one of the SQLITE_ success/failure
@@ -70304,17 +70891,16 @@
70304 const char *zSql, /* The SQL to be executed */
70305 sqlite3_callback xCallback, /* Invoke this callback routine */
70306 void *pArg, /* First argument to xCallback() */
70307 char **pzErrMsg /* Write error messages here */
70308 ){
70309 int rc = SQLITE_OK;
70310 const char *zLeftover;
70311 sqlite3_stmt *pStmt = 0;
70312 char **azCols = 0;
70313
70314 int nRetry = 0;
70315 int nCallback;
70316
70317 if( zSql==0 ) zSql = "";
70318
70319 sqlite3_mutex_enter(db->mutex);
70320 sqlite3Error(db, SQLITE_OK, 0);
@@ -70332,34 +70918,33 @@
70332 /* this happens for a comment or white-space */
70333 zSql = zLeftover;
70334 continue;
70335 }
70336
70337 nCallback = 0;
70338 nCol = sqlite3_column_count(pStmt);
70339
70340 while( 1 ){
70341 int i;
70342 rc = sqlite3_step(pStmt);
70343
70344 /* Invoke the callback function if required */
70345 if( xCallback && (SQLITE_ROW==rc ||
70346 (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){
70347 if( 0==nCallback ){
 
 
70348 if( azCols==0 ){
70349 azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
70350 if( azCols==0 ){
70351 goto exec_out;
70352 }
70353 }
70354 for(i=0; i<nCol; i++){
70355 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
70356 /* sqlite3VdbeSetColName() installs column names as UTF8
70357 ** strings so there is no way for sqlite3_column_name() to fail. */
70358 assert( azCols[i]!=0 );
70359 }
70360 nCallback++;
70361 }
70362 if( rc==SQLITE_ROW ){
70363 azVals = &azCols[nCol];
70364 for(i=0; i<nCol; i++){
70365 azVals[i] = (char *)sqlite3_column_text(pStmt, i);
@@ -70397,11 +70982,11 @@
70397 exec_out:
70398 if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
70399 sqlite3DbFree(db, azCols);
70400
70401 rc = sqlite3ApiExit(db, rc);
70402 if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
70403 int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
70404 *pzErrMsg = sqlite3Malloc(nErrMsg);
70405 if( *pzErrMsg ){
70406 memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
70407 }
@@ -72848,11 +73433,11 @@
72848 *************************************************************************
72849 ** This file contains the implementation of the sqlite3_prepare()
72850 ** interface, and routines that contribute to loading the database schema
72851 ** from disk.
72852 **
72853 ** $Id: prepare.c,v 1.116 2009/04/02 18:32:27 drh Exp $
72854 */
72855
72856 /*
72857 ** Fill the InitData structure with an error message that indicates
72858 ** that the database is corrupt.
@@ -72961,10 +73546,11 @@
72961 ** auxiliary databases. Return one of the SQLITE_ error codes to
72962 ** indicate success or failure.
72963 */
72964 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
72965 int rc;
 
72966 BtCursor *curMain;
72967 int size;
72968 Table *pTab;
72969 Db *pDb;
72970 char const *azArg[4];
@@ -73050,11 +73636,12 @@
73050 rc = SQLITE_NOMEM;
73051 goto error_out;
73052 }
73053 sqlite3BtreeEnter(pDb->pBt);
73054 rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, curMain);
73055 if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){
 
73056 sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
73057 goto initone_error_out;
73058 }
73059
73060 /* Get the database meta information.
@@ -73072,21 +73659,16 @@
73072 ** meta[9]
73073 **
73074 ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
73075 ** the possible values of meta[4].
73076 */
73077 if( rc==SQLITE_OK ){
73078 int i;
73079 for(i=0; i<ArraySize(meta); i++){
73080 rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
73081 if( rc ){
73082 sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
73083 goto initone_error_out;
73084 }
73085 }
73086 }else{
73087 memset(meta, 0, sizeof(meta));
73088 }
73089 pDb->pSchema->schema_cookie = meta[0];
73090
73091 /* If opening a non-empty database, check the text encoding. For the
73092 ** main database, set sqlite3.enc to the encoding of the main database.
@@ -73683,11 +74265,11 @@
73683 **
73684 *************************************************************************
73685 ** This file contains C code routines that are called by the parser
73686 ** to handle SELECT statements in SQLite.
73687 **
73688 ** $Id: select.c,v 1.507 2009/04/02 16:59:47 drh Exp $
73689 */
73690
73691
73692 /*
73693 ** Delete all the content of a Select structure but do not deallocate
@@ -73863,46 +74445,11 @@
73863 */
73864 static void setToken(Token *p, const char *z){
73865 p->z = (u8*)z;
73866 p->n = z ? sqlite3Strlen30(z) : 0;
73867 p->dyn = 0;
73868 }
73869
73870 /*
73871 ** Set the token to the double-quoted and escaped version of the string pointed
73872 ** to by z. For example;
73873 **
73874 ** {a"bc} -> {"a""bc"}
73875 */
73876 static void setQuotedToken(Parse *pParse, Token *p, const char *z){
73877
73878 /* Check if the string appears to be quoted using "..." or `...`
73879 ** or [...] or '...' or if the string contains any " characters.
73880 ** If it does, then record a version of the string with the special
73881 ** characters escaped.
73882 */
73883 const char *z2 = z;
73884 if( *z2!='[' && *z2!='`' && *z2!='\'' ){
73885 while( *z2 ){
73886 if( *z2=='"' ) break;
73887 z2++;
73888 }
73889 }
73890
73891 if( *z2 ){
73892 /* String contains " characters - copy and quote the string. */
73893 p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
73894 if( p->z ){
73895 p->n = sqlite3Strlen30((char *)p->z);
73896 p->dyn = 1;
73897 }
73898 }else{
73899 /* String contains no " characters - copy the pointer. */
73900 p->z = (u8*)z;
73901 p->n = (int)(z2 - z);
73902 p->dyn = 0;
73903 }
73904 }
73905
73906 /*
73907 ** Create an expression node for an identifier with the name of zName
73908 */
@@ -74091,10 +74638,11 @@
74091 ){
74092 Vdbe *v = pParse->pVdbe;
74093 int nExpr = pOrderBy->nExpr;
74094 int regBase = sqlite3GetTempRange(pParse, nExpr+2);
74095 int regRecord = sqlite3GetTempReg(pParse);
 
74096 sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
74097 sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
74098 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
74099 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
74100 sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
@@ -74243,10 +74791,11 @@
74243 }
74244 }else if( eDest!=SRT_Exists ){
74245 /* If the destination is an EXISTS(...) expression, the actual
74246 ** values returned by the SELECT are not required.
74247 */
 
74248 sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
74249 }
74250 nColumn = nResultCol;
74251
74252 /* If the DISTINCT keyword was present on the SELECT statement
@@ -74860,11 +75409,10 @@
74860 }
74861 if( db->mallocFailed ){
74862 sqlite3DbFree(db, zName);
74863 break;
74864 }
74865 sqlite3Dequote(zName);
74866
74867 /* Make sure the column name is unique. If the name is not unique,
74868 ** append a integer to the name so that it becomes unique.
74869 */
74870 nName = sqlite3Strlen30(zName);
@@ -75016,10 +75564,11 @@
75016 ** "LIMIT -1" always shows all rows. There is some
75017 ** contraversy about what the correct behavior should be.
75018 ** The current implementation interprets "LIMIT 0" to mean
75019 ** no rows.
75020 */
 
75021 if( p->pLimit ){
75022 p->iLimit = iLimit = ++pParse->nMem;
75023 v = sqlite3GetVdbe(pParse);
75024 if( v==0 ) return;
75025 sqlite3ExprCode(pParse, p->pLimit, iLimit);
@@ -75064,11 +75613,12 @@
75064 if( p->pPrior ){
75065 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
75066 }else{
75067 pRet = 0;
75068 }
75069 if( pRet==0 ){
 
75070 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
75071 }
75072 return pRet;
75073 }
75074 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
@@ -75771,11 +76321,11 @@
75771 }
75772 }
75773 }
75774
75775 /* Compute the comparison permutation and keyinfo that is used with
75776 ** the permutation in order to comparisons to determine if the next
75777 ** row of results comes from selectA or selectB. Also add explicit
75778 ** collations to the ORDER BY clause terms so that when the subqueries
75779 ** to the right and the left are evaluated, they use the correct
75780 ** collation.
75781 */
@@ -76894,16 +77444,16 @@
76894 continue;
76895 }
76896 }
76897 pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
76898 if( pRight==0 ) break;
76899 setQuotedToken(pParse, &pRight->token, zName);
76900 if( longNames || pTabList->nSrc>1 ){
76901 Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
76902 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
76903 if( pExpr==0 ) break;
76904 setQuotedToken(pParse, &pLeft->token, zTabName);
76905 setToken(&pExpr->span,
76906 sqlite3MPrintf(db, "%s.%s", zTabName, zName));
76907 pExpr->span.dyn = 1;
76908 pExpr->token.z = 0;
76909 pExpr->token.n = 0;
@@ -77125,10 +77675,11 @@
77125 int i;
77126 struct AggInfo_func *pF;
77127 struct AggInfo_col *pC;
77128
77129 pAggInfo->directMode = 1;
 
77130 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
77131 int nArg;
77132 int addrNext = 0;
77133 int regAgg;
77134 ExprList *pList = pF->pExpr->x.pList;
@@ -77164,16 +77715,18 @@
77164 sqlite3VdbeChangeP5(v, (u8)nArg);
77165 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
77166 sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
77167 if( addrNext ){
77168 sqlite3VdbeResolveLabel(v, addrNext);
 
77169 }
77170 }
77171 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
77172 sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
77173 }
77174 pAggInfo->directMode = 0;
 
77175 }
77176
77177 /*
77178 ** Generate code for the SELECT statement given in the p argument.
77179 **
@@ -77434,11 +77987,11 @@
77434 /* Aggregate and non-aggregate queries are handled differently */
77435 if( !isAgg && pGroupBy==0 ){
77436 /* This case is for non-aggregate queries
77437 ** Begin the database scan
77438 */
77439 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0, 0);
77440 if( pWInfo==0 ) goto select_end;
77441
77442 /* If sorting index that was created by a prior OP_OpenEphemeral
77443 ** instruction ended up not being needed, then change the OP_OpenEphemeral
77444 ** into an OP_Noop.
@@ -77556,11 +78109,11 @@
77556 ** This might involve two separate loops with an OP_Sort in between, or
77557 ** it might be a single loop that uses an index to extract information
77558 ** in the right order to begin with.
77559 */
77560 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
77561 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0);
77562 if( pWInfo==0 ) goto select_end;
77563 if( pGroupBy==0 ){
77564 /* The optimizer is able to deliver rows in group by order so
77565 ** we do not have to sort. The OP_OpenEphemeral table will be
77566 ** cancelled later because we still need to use the pKeyInfo
@@ -77587,10 +78140,11 @@
77587 nCol++;
77588 j++;
77589 }
77590 }
77591 regBase = sqlite3GetTempRange(pParse, nCol);
 
77592 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
77593 sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
77594 j = nGroupBy+1;
77595 for(i=0; i<sAggInfo.nColumn; i++){
77596 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
@@ -77613,18 +78167,20 @@
77613 sqlite3ReleaseTempRange(pParse, regBase, nCol);
77614 sqlite3WhereEnd(pWInfo);
77615 sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
77616 VdbeComment((v, "GROUP BY sort"));
77617 sAggInfo.useSortingIdx = 1;
 
77618 }
77619
77620 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
77621 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
77622 ** Then compare the current GROUP BY terms against the GROUP BY terms
77623 ** from the previous row currently stored in a0, a1, a2...
77624 */
77625 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
 
77626 for(j=0; j<pGroupBy->nExpr; j++){
77627 if( groupBySort ){
77628 sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
77629 }else{
77630 sAggInfo.directMode = 1;
@@ -77811,11 +78367,11 @@
77811 /* This case runs if the aggregate has no GROUP BY clause. The
77812 ** processing is much simpler since there is only a single row
77813 ** of output.
77814 */
77815 resetAccumulator(pParse, &sAggInfo);
77816 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag, 0);
77817 if( pWInfo==0 ){
77818 sqlite3ExprListDelete(db, pDel);
77819 goto select_end;
77820 }
77821 updateAccumulator(pParse, &sAggInfo);
@@ -78179,11 +78735,11 @@
78179 ** May you share freely, never taking more than you give.
78180 **
78181 *************************************************************************
78182 **
78183 **
78184 ** $Id: trigger.c,v 1.135 2009/02/28 10:47:42 danielk1977 Exp $
78185 */
78186
78187 #ifndef SQLITE_OMIT_TRIGGER
78188 /*
78189 ** Delete a linked list of TriggerStep structures.
@@ -78453,11 +79009,11 @@
78453 pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
78454 if( pTrig ){
78455 db->mallocFailed = 1;
78456 }else if( pLink->pSchema==pLink->pTabSchema ){
78457 Table *pTab;
78458 int n = sqlite3Strlen30(pLink->table) + 1;
78459 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
78460 assert( pTab!=0 );
78461 pLink->pNext = pTab->pTrigger;
78462 pTab->pTrigger = pLink;
78463 }
@@ -78680,11 +79236,11 @@
78680 /*
78681 ** Return a pointer to the Table structure for the table that a trigger
78682 ** is set on.
78683 */
78684 static Table *tableOfTrigger(Trigger *pTrigger){
78685 int n = sqlite3Strlen30(pTrigger->table) + 1;
78686 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
78687 }
78688
78689
78690 /*
@@ -78831,10 +79387,11 @@
78831 iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
78832 if( iDb==0 || iDb>=2 ){
78833 assert( iDb<pParse->db->nDb );
78834 sDb.z = (u8*)pParse->db->aDb[iDb].zName;
78835 sDb.n = sqlite3Strlen30((char*)sDb.z);
 
78836 pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target);
78837 } else {
78838 pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
78839 }
78840 return pSrc;
@@ -78857,11 +79414,11 @@
78857 assert( pTriggerStep!=0 );
78858 assert( v!=0 );
78859 sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0);
78860 VdbeComment((v, "begin trigger %s", pStepList->pTrig->name));
78861 while( pTriggerStep ){
78862 sqlite3ExprClearColumnCache(pParse, -1);
78863 orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
78864 pParse->trigStack->orconf = orconf;
78865 switch( pTriggerStep->op ){
78866 case TK_SELECT: {
78867 Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect, 0);
@@ -79056,11 +79613,11 @@
79056 **
79057 *************************************************************************
79058 ** This file contains C code routines that are called by the parser
79059 ** to handle UPDATE statements.
79060 **
79061 ** $Id: update.c,v 1.196 2009/02/28 10:47:42 danielk1977 Exp $
79062 */
79063
79064 #ifndef SQLITE_OMIT_VIRTUALTABLE
79065 /* Forward declaration */
79066 static void updateVirtualTable(
@@ -79098,11 +79655,12 @@
79098 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
79099 ** function is capable of transforming these types of expressions into
79100 ** sqlite3_value objects.
79101 */
79102 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
79103 if( pTab && !pTab->pSelect ){
 
79104 sqlite3_value *pValue;
79105 u8 enc = ENC(sqlite3VdbeDb(v));
79106 Column *pCol = &pTab->aCol[i];
79107 VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
79108 assert( i<pTab->nCol );
@@ -79388,18 +79946,17 @@
79388 }
79389
79390 /* Begin the database scan
79391 */
79392 sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
79393 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0,
79394 WHERE_ONEPASS_DESIRED, 0);
79395 if( pWInfo==0 ) goto update_cleanup;
79396 okOnePass = pWInfo->okOnePass;
79397
79398 /* Remember the rowid of every item to be updated.
79399 */
79400 sqlite3VdbeAddOp2(v, IsVirtual(pTab)?OP_VRowid:OP_Rowid, iCur, regOldRowid);
79401 if( !okOnePass ){
79402 regRowSet = ++pParse->nMem;
79403 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
79404 }
79405
@@ -79412,11 +79969,11 @@
79412 if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
79413 regRowCount = ++pParse->nMem;
79414 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
79415 }
79416
79417 if( !isView && !IsVirtual(pTab) ){
79418 /*
79419 ** Open every index that needs updating. Note that if any
79420 ** index could potentially invoke a REPLACE conflict resolution
79421 ** action, then we need to open all indices because we might need
79422 ** to be deleting some records.
@@ -79491,11 +80048,11 @@
79491 if( i==pTab->iPKey ){
79492 sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
79493 continue;
79494 }
79495 j = aXRef[i];
79496 if( new_col_mask&((u32)1<<i) || new_col_mask==0xffffffff ){
79497 if( j<0 ){
79498 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regCols+i);
79499 sqlite3ColumnDefault(v, pTab, i);
79500 }else{
79501 sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr, regCols+i);
@@ -79517,11 +80074,11 @@
79517
79518 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
79519 sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
79520 }
79521
79522 if( !isView && !IsVirtual(pTab) ){
79523 /* Loop over every record that needs updating. We have to load
79524 ** the old data for each record to be updated because some columns
79525 ** might not change and we will need to copy the old value.
79526 ** Also, the old data is needed to delete the old index entries.
79527 ** So make the cursor point at the old record.
@@ -79555,11 +80112,11 @@
79555
79556 /* Do constraint checks
79557 */
79558 sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
79559 aRegIdx, chngRowid, 1,
79560 onError, addr);
79561
79562 /* Delete the old indices for the current record.
79563 */
79564 j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
79565 sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
@@ -79572,11 +80129,11 @@
79572 sqlite3VdbeJumpHere(v, j1);
79573
79574 /* Create the new index entries and the new record.
79575 */
79576 sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid,
79577 aRegIdx, 1, -1, 0);
79578 }
79579
79580 /* Increment the row counter
79581 */
79582 if( db->flags & SQLITE_CountRows && !pParse->trigStack){
@@ -79745,26 +80302,28 @@
79745 ** This file contains code used to implement the VACUUM command.
79746 **
79747 ** Most of the code in this file may be omitted by defining the
79748 ** SQLITE_OMIT_VACUUM macro.
79749 **
79750 ** $Id: vacuum.c,v 1.87 2009/04/02 20:16:59 drh Exp $
79751 */
79752
79753 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
79754 /*
79755 ** Execute zSql on database db. Return an error code.
79756 */
79757 static int execSql(sqlite3 *db, const char *zSql){
79758 sqlite3_stmt *pStmt;
 
79759 if( !zSql ){
79760 return SQLITE_NOMEM;
79761 }
79762 if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
79763 return sqlite3_errcode(db);
79764 }
79765 while( SQLITE_ROW==sqlite3_step(pStmt) ){}
 
79766 return sqlite3_finalize(pStmt);
79767 }
79768
79769 /*
79770 ** Execute zSql on database db. The statement returns exactly
@@ -79871,11 +80430,11 @@
79871 }
79872 #endif
79873
79874 if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
79875 || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
79876 || db->mallocFailed
79877 ){
79878 rc = SQLITE_NOMEM;
79879 goto end_of_vacuum;
79880 }
79881 rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
@@ -79959,11 +80518,11 @@
79959 ** call to sqlite3BtreeCopyFile(). The main database btree level
79960 ** transaction is then committed, so the SQL level never knows it was
79961 ** opened for writing. This way, the SQL transaction used to create the
79962 ** temporary database never needs to be committed.
79963 */
79964 if( rc==SQLITE_OK ){
79965 u32 meta;
79966 int i;
79967
79968 /* This array determines which meta meta values are preserved in the
79969 ** vacuum. Even entries are the meta value number and odd entries
@@ -79981,14 +80540,16 @@
79981 assert( 1==sqlite3BtreeIsInTrans(pTemp) );
79982 assert( 1==sqlite3BtreeIsInTrans(pMain) );
79983
79984 /* Copy Btree meta values */
79985 for(i=0; i<ArraySize(aCopy); i+=2){
 
 
79986 rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
79987 if( rc!=SQLITE_OK ) goto end_of_vacuum;
79988 rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
79989 if( rc!=SQLITE_OK ) goto end_of_vacuum;
79990 }
79991
79992 rc = sqlite3BtreeCopyFile(pMain, pTemp);
79993 if( rc!=SQLITE_OK ) goto end_of_vacuum;
79994 rc = sqlite3BtreeCommit(pTemp);
@@ -79996,13 +80557,12 @@
79996 #ifndef SQLITE_OMIT_AUTOVACUUM
79997 sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
79998 #endif
79999 }
80000
80001 if( rc==SQLITE_OK ){
80002 rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
80003 }
80004
80005 end_of_vacuum:
80006 /* Restore the original value of db->flags */
80007 db->flags = saved_flags;
80008 db->nChange = saved_nChange;
@@ -80042,11 +80602,11 @@
80042 ** May you share freely, never taking more than you give.
80043 **
80044 *************************************************************************
80045 ** This file contains code used to help implement virtual tables.
80046 **
80047 ** $Id: vtab.c,v 1.85 2009/04/11 16:27:20 drh Exp $
80048 */
80049 #ifndef SQLITE_OMIT_VIRTUALTABLE
80050
80051 /*
80052 ** The actual function that does the work of creating a new module.
@@ -80338,11 +80898,11 @@
80338 */
80339 else {
80340 Table *pOld;
80341 Schema *pSchema = pTab->pSchema;
80342 const char *zName = pTab->zName;
80343 int nName = sqlite3Strlen30(zName) + 1;
80344 pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
80345 if( pOld ){
80346 db->mallocFailed = 1;
80347 assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
80348 return;
@@ -80901,11 +81461,11 @@
80901 ** generating the code that loops through a table looking for applicable
80902 ** rows. Indices are selected and used to speed the search when doing
80903 ** so is applicable. Because this module is responsible for selecting
80904 ** indices, you might also think of this module as the "query optimizer".
80905 **
80906 ** $Id: where.c,v 1.382 2009/04/07 13:48:12 drh Exp $
80907 */
80908
80909 /*
80910 ** Trace output macros
80911 */
@@ -80927,14 +81487,12 @@
80927 typedef struct WhereCost WhereCost;
80928
80929 /*
80930 ** The query generator uses an array of instances of this structure to
80931 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
80932 ** clause subexpression is separated from the others by AND operators.
80933 ** (Note: the same data structure is also reused to hold a group of terms
80934 ** separated by OR operators. But at the top-level, everything is AND
80935 ** separated.)
80936 **
80937 ** All WhereTerms are collected into a single WhereClause structure.
80938 ** The following identity holds:
80939 **
80940 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
@@ -81112,15 +81670,16 @@
81112 ** ISNULL constraints will then not be used on the right table of a left
81113 ** join. Tickets #2177 and #2189.
81114 */
81115 #define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
81116 #define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
81117 #define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) */
81118 #define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
81119 #define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
81120 #define WHERE_INDEXED 0x00070000 /* Anything that uses an index */
81121 #define WHERE_IN_ABLE 0x00071000 /* Able to support an IN operator */
 
81122 #define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
81123 #define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
81124 #define WHERE_IDX_ONLY 0x00800000 /* Use index only - omit table */
81125 #define WHERE_ORDERBY 0x01000000 /* Output will appear in correct order */
81126 #define WHERE_REVERSE 0x02000000 /* Scan in reverse order */
@@ -81259,20 +81818,21 @@
81259 whereSplit(pWC, pExpr->pRight, op);
81260 }
81261 }
81262
81263 /*
81264 ** Initialize an expression mask set
81265 */
81266 #define initMaskSet(P) memset(P, 0, sizeof(*P))
81267
81268 /*
81269 ** Return the bitmask for the given cursor number. Return 0 if
81270 ** iCursor is not in the set.
81271 */
81272 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
81273 int i;
 
81274 for(i=0; i<pMaskSet->n; i++){
81275 if( pMaskSet->ix[i]==iCursor ){
81276 return ((Bitmask)1)<<i;
81277 }
81278 }
@@ -81510,10 +82070,11 @@
81510 ){
81511 const char *z; /* String on RHS of LIKE operator */
81512 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
81513 ExprList *pList; /* List of operands to the LIKE operator */
81514 int c; /* One character in z[] */
 
81515 int cnt; /* Number of non-wildcard prefix characters */
81516 char wc[3]; /* Wildcard characters */
81517 CollSeq *pColl; /* Collating sequence for LHS */
81518 sqlite3 *db = pParse->db; /* Database connection */
81519
@@ -81540,15 +82101,17 @@
81540 }
81541 if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
81542 (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
81543 return 0;
81544 }
81545 sqlite3DequoteExpr(pRight);
81546 z = (char *)pRight->token.z;
81547 cnt = 0;
81548 if( z ){
81549 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; }
 
 
 
81550 }
81551 if( cnt==0 || 255==(u8)z[cnt-1] ){
81552 return 0;
81553 }
81554 *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
@@ -82045,11 +82608,10 @@
82045 pRight = pExpr->x.pList->a[0].pExpr;
82046 pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
82047 if( pStr1 ){
82048 sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
82049 pStr1->token.n = nPattern;
82050 pStr1->flags = EP_Dequoted;
82051 }
82052 pStr2 = sqlite3ExprDup(db, pStr1, 0);
82053 if( !db->mallocFailed ){
82054 u8 c, *pC;
82055 /* assert( pStr2->token.dyn ); */
@@ -82358,12 +82920,251 @@
82358 }
82359 #else
82360 #define TRACE_IDX_INPUTS(A)
82361 #define TRACE_IDX_OUTPUTS(A)
82362 #endif
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82363
82364 #ifndef SQLITE_OMIT_VIRTUALTABLE
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82365 /*
82366 ** Compute the best index for a virtual table.
82367 **
82368 ** The best index is computed by the xBestIndex method of the virtual
82369 ** table module. This routine is really just a wrapper that sets up
@@ -82376,118 +83177,43 @@
82376 ** invocations. The sqlite3_index_info structure is also used when
82377 ** code is generated to access the virtual table. The whereInfoDelete()
82378 ** routine takes care of freeing the sqlite3_index_info structure after
82379 ** everybody has finished with it.
82380 */
82381 static double bestVirtualIndex(
82382 Parse *pParse, /* The parsing context */
82383 WhereClause *pWC, /* The WHERE clause */
82384 struct SrcList_item *pSrc, /* The FROM clause term to search */
82385 Bitmask notReady, /* Mask of cursors that are not available */
82386 ExprList *pOrderBy, /* The order by clause */
82387 int orderByUsable, /* True if we can potential sort */
82388 sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
82389 ){
82390 Table *pTab = pSrc->pTab;
82391 sqlite3_vtab *pVtab = pTab->pVtab;
82392 sqlite3_index_info *pIdxInfo;
82393 struct sqlite3_index_constraint *pIdxCons;
82394 struct sqlite3_index_orderby *pIdxOrderBy;
82395 struct sqlite3_index_constraint_usage *pUsage;
82396 WhereTerm *pTerm;
82397 int i, j;
82398 int nOrderBy;
82399 int rc;
 
 
 
 
 
 
82400
82401 /* If the sqlite3_index_info structure has not been previously
82402 ** allocated and initialized for this virtual table, then allocate
82403 ** and initialize it now
82404 */
82405 pIdxInfo = *ppIdxInfo;
82406 if( pIdxInfo==0 ){
82407 int nTerm;
82408 WHERETRACE(("Recomputing index info for %s...\n", pTab->zName));
82409
82410 /* Count the number of possible WHERE clause constraints referring
82411 ** to this virtual table */
82412 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
82413 if( pTerm->leftCursor != pSrc->iCursor ) continue;
82414 assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
82415 testcase( pTerm->eOperator==WO_IN );
82416 testcase( pTerm->eOperator==WO_ISNULL );
82417 if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
82418 nTerm++;
82419 }
82420
82421 /* If the ORDER BY clause contains only columns in the current
82422 ** virtual table then allocate space for the aOrderBy part of
82423 ** the sqlite3_index_info structure.
82424 */
82425 nOrderBy = 0;
82426 if( pOrderBy ){
82427 for(i=0; i<pOrderBy->nExpr; i++){
82428 Expr *pExpr = pOrderBy->a[i].pExpr;
82429 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
82430 }
82431 if( i==pOrderBy->nExpr ){
82432 nOrderBy = pOrderBy->nExpr;
82433 }
82434 }
82435
82436 /* Allocate the sqlite3_index_info structure
82437 */
82438 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
82439 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
82440 + sizeof(*pIdxOrderBy)*nOrderBy );
82441 if( pIdxInfo==0 ){
82442 sqlite3ErrorMsg(pParse, "out of memory");
82443 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
82444 return (double)0;
82445 }
82446 *ppIdxInfo = pIdxInfo;
82447
82448 /* Initialize the structure. The sqlite3_index_info structure contains
82449 ** many fields that are declared "const" to prevent xBestIndex from
82450 ** changing them. We have to do some funky casting in order to
82451 ** initialize those fields.
82452 */
82453 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
82454 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
82455 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
82456 *(int*)&pIdxInfo->nConstraint = nTerm;
82457 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
82458 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
82459 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
82460 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
82461 pUsage;
82462
82463 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
82464 if( pTerm->leftCursor != pSrc->iCursor ) continue;
82465 assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
82466 testcase( pTerm->eOperator==WO_IN );
82467 testcase( pTerm->eOperator==WO_ISNULL );
82468 if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
82469 pIdxCons[j].iColumn = pTerm->u.leftColumn;
82470 pIdxCons[j].iTermOffset = i;
82471 pIdxCons[j].op = (u8)pTerm->eOperator;
82472 /* The direct assignment in the previous line is possible only because
82473 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
82474 ** following asserts verify this fact. */
82475 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
82476 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
82477 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
82478 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
82479 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
82480 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
82481 assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
82482 j++;
82483 }
82484 for(i=0; i<nOrderBy; i++){
82485 Expr *pExpr = pOrderBy->a[i].pExpr;
82486 pIdxOrderBy[i].iColumn = pExpr->iColumn;
82487 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
82488 }
82489 }
82490
82491 /* At this point, the sqlite3_index_info structure that pIdxInfo points
82492 ** to will have been initialized, either during the current invocation or
82493 ** during some prior invocation. Now we just have to customize the
@@ -82498,18 +83224,11 @@
82498 /* The module name must be defined. Also, by this point there must
82499 ** be a pointer to an sqlite3_vtab structure. Otherwise
82500 ** sqlite3ViewGetColumnNames() would have picked up the error.
82501 */
82502 assert( pTab->azModuleArg && pTab->azModuleArg[0] );
82503 assert( pVtab );
82504 #if 0
82505 if( pTab->pVtab==0 ){
82506 sqlite3ErrorMsg(pParse, "undefined module %s for table %s",
82507 pTab->azModuleArg[0], pTab->zName);
82508 return 0.0;
82509 }
82510 #endif
82511
82512 /* Set the aConstraint[].usable fields and initialize all
82513 ** output variables to zero.
82514 **
82515 ** aConstraint[].usable is true for constraints where the right-hand
@@ -82545,44 +83264,41 @@
82545 pIdxInfo->needToFreeIdxStr = 0;
82546 pIdxInfo->orderByConsumed = 0;
82547 /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
82548 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
82549 nOrderBy = pIdxInfo->nOrderBy;
82550 if( pIdxInfo->nOrderBy && !orderByUsable ){
82551 *(int*)&pIdxInfo->nOrderBy = 0;
82552 }
82553
82554 (void)sqlite3SafetyOff(pParse->db);
82555 WHERETRACE(("xBestIndex for %s\n", pTab->zName));
82556 TRACE_IDX_INPUTS(pIdxInfo);
82557 rc = pVtab->pModule->xBestIndex(pVtab, pIdxInfo);
82558 TRACE_IDX_OUTPUTS(pIdxInfo);
82559 (void)sqlite3SafetyOn(pParse->db);
82560
82561 if( rc!=SQLITE_OK ){
82562 if( rc==SQLITE_NOMEM ){
82563 pParse->db->mallocFailed = 1;
82564 }else if( !pVtab->zErrMsg ){
82565 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
82566 }else{
82567 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
82568 }
82569 }
82570 sqlite3DbFree(pParse->db, pVtab->zErrMsg);
82571 pVtab->zErrMsg = 0;
82572
82573 for(i=0; i<pIdxInfo->nConstraint; i++){
82574 if( !pIdxInfo->aConstraint[i].usable && pUsage[i].argvIndex>0 ){
82575 sqlite3ErrorMsg(pParse,
82576 "table %s: xBestIndex returned an invalid plan", pTab->zName);
82577 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
82578 return (double)0;
82579 }
82580 }
82581
82582 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
82583 return pIdxInfo->estimatedCost;
82584 }
82585 #endif /* SQLITE_OMIT_VIRTUALTABLE */
82586
82587 /*
82588 ** Find the query plan for accessing a particular table. Write the
@@ -82610,11 +83326,11 @@
82610 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
82611 ** in the SELECT statement, then no indexes are considered. However, the
82612 ** selected plan may still take advantage of the tables built-in rowid
82613 ** index.
82614 */
82615 static void bestIndex(
82616 Parse *pParse, /* The parsing context */
82617 WhereClause *pWC, /* The WHERE clause */
82618 struct SrcList_item *pSrc, /* The FROM clause term to search */
82619 Bitmask notReady, /* Mask of cursors that are not available */
82620 ExprList *pOrderBy, /* The ORDER BY clause */
@@ -82628,11 +83344,10 @@
82628 int nEq; /* Number of == or IN constraints */
82629 int eqTermMask; /* Mask of valid equality operators */
82630 double cost; /* Cost of using pProbe */
82631 double nRow; /* Estimated number of rows in result set */
82632 int i; /* Loop counter */
82633 Bitmask maskSrc; /* Bitmask for the pSrc table */
82634
82635 WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName,notReady));
82636 pProbe = pSrc->pTab->pIndex;
82637 if( pSrc->notIndexed ){
82638 pProbe = 0;
@@ -82744,65 +83459,11 @@
82744 pCost->nRow = nRow;
82745 pCost->plan.wsFlags = wsFlags;
82746 }
82747 }
82748
82749 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
82750 /* Search for an OR-clause that can be used to look up the table.
82751 */
82752 maskSrc = getMask(pWC->pMaskSet, iCur);
82753 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
82754 WhereClause tempWC;
82755 tempWC = *pWC;
82756 if( pTerm->eOperator==WO_OR
82757 && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
82758 && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 ){
82759 WhereClause *pOrWC = &pTerm->u.pOrInfo->wc;
82760 WhereTerm *pOrTerm;
82761 int j;
82762 int sortable = 0;
82763 double rTotal = 0;
82764 nRow = 0;
82765 for(j=0, pOrTerm=pOrWC->a; j<pOrWC->nTerm; j++, pOrTerm++){
82766 WhereCost sTermCost;
82767 WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", j,i));
82768 if( pOrTerm->eOperator==WO_AND ){
82769 WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
82770 bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
82771 }else if( pOrTerm->leftCursor==iCur ){
82772 tempWC.a = pOrTerm;
82773 tempWC.nTerm = 1;
82774 bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
82775 }else{
82776 continue;
82777 }
82778 rTotal += sTermCost.rCost;
82779 nRow += sTermCost.nRow;
82780 if( rTotal>=pCost->rCost ) break;
82781 }
82782 if( pOrderBy!=0 ){
82783 if( sortableByRowid(iCur, pOrderBy, pWC->pMaskSet, &rev) && !rev ){
82784 sortable = 1;
82785 }else{
82786 rTotal += nRow*estLog(nRow);
82787 WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
82788 }
82789 }
82790 WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n",
82791 rTotal, nRow));
82792 if( rTotal<pCost->rCost ){
82793 pCost->rCost = rTotal;
82794 pCost->nRow = nRow;
82795 pCost->plan.wsFlags = WHERE_MULTI_OR;
82796 pCost->plan.u.pTerm = pTerm;
82797 if( sortable ){
82798 pCost->plan.wsFlags = WHERE_ORDERBY|WHERE_MULTI_OR;
82799 }
82800 }
82801 }
82802 }
82803 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
82804
82805 /* If the pSrc table is the right table of a LEFT JOIN then we may not
82806 ** use an index to satisfy IS NULL constraints on that table. This is
82807 ** because columns might end up being NULL if the table does not match -
82808 ** a circumstance which the index cannot help us discover. Ticket #2177.
@@ -82823,13 +83484,14 @@
82823 int inMultIsEst = 0; /* True if inMultiplier is an estimate */
82824
82825 WHERETRACE(("... index %s:\n", pProbe->zName));
82826
82827 /* Count the number of columns in the index that are satisfied
82828 ** by x=EXPR constraints or x IN (...) constraints. For a term
82829 ** of the form x=EXPR we only have to do a single binary search.
82830 ** But for x IN (...) we have to do a number of binary searched
 
82831 ** equal to the number of entries on the RHS of the IN operator.
82832 ** The inMultipler variable with try to estimate the number of
82833 ** binary searches needed.
82834 */
82835 wsFlags = 0;
@@ -82845,10 +83507,12 @@
82845 inMultiplier *= 25;
82846 inMultIsEst = 1;
82847 }else if( pExpr->x.pList ){
82848 inMultiplier *= pExpr->x.pList->nExpr + 1;
82849 }
 
 
82850 }
82851 }
82852 nRow = pProbe->aiRowEst[i] * inMultiplier;
82853 /* If inMultiplier is an estimate and that estimate results in an
82854 ** nRow it that is more than half number of rows in the table,
@@ -82857,13 +83521,16 @@
82857 nRow = pProbe->aiRowEst[0]/2;
82858 inMultiplier = nRow/pProbe->aiRowEst[i];
82859 }
82860 cost = nRow + inMultiplier*estLog(pProbe->aiRowEst[0]);
82861 nEq = i;
82862 if( pProbe->onError!=OE_None && (wsFlags & WHERE_COLUMN_IN)==0
82863 && nEq==pProbe->nColumn ){
82864 wsFlags |= WHERE_UNIQUE;
 
 
 
82865 }
82866 WHERETRACE(("...... nEq=%d inMult=%.9g nRow=%.9g cost=%.9g\n",
82867 nEq, inMultiplier, nRow, cost));
82868
82869 /* Look for range constraints. Assume that each range constraint
@@ -82890,12 +83557,13 @@
82890 }
82891
82892 /* Add the additional cost of sorting if that is a factor.
82893 */
82894 if( pOrderBy ){
82895 if( (wsFlags & WHERE_COLUMN_IN)==0 &&
82896 isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev) ){
 
82897 if( wsFlags==0 ){
82898 wsFlags = WHERE_COLUMN_RANGE;
82899 }
82900 wsFlags |= WHERE_ORDERBY;
82901 if( rev ){
@@ -82952,10 +83620,35 @@
82952 (pCost->plan.wsFlags & WHERE_INDEXED)!=0 ?
82953 pCost->plan.u.pIdx->zName : "(none)", pCost->nRow,
82954 pCost->rCost, pCost->plan.wsFlags, pCost->plan.nEq));
82955 }
82956
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82957
82958 /*
82959 ** Disable a term in the WHERE clause. Except, do not disable the term
82960 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
82961 ** or USING clause of that join.
@@ -83148,37 +83841,18 @@
83148 }
83149 }
83150 return regBase;
83151 }
83152
83153 /*
83154 ** Return TRUE if the WhereClause pWC contains no terms that
83155 ** are not virtual and which have not been coded.
83156 **
83157 ** To put it another way, return TRUE if no additional WHERE clauses
83158 ** tests are required in order to establish that the current row
83159 ** should go to output and return FALSE if there are some terms of
83160 ** the WHERE clause that need to be validated before outputing the row.
83161 */
83162 static int whereRowReadyForOutput(WhereClause *pWC){
83163 WhereTerm *pTerm;
83164 int j;
83165
83166 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
83167 if( (pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED))==0 ) return 0;
83168 }
83169 return 1;
83170 }
83171
83172 /*
83173 ** Generate code for the start of the iLevel-th loop in the WHERE clause
83174 ** implementation described by pWInfo.
83175 */
83176 static Bitmask codeOneLoopStart(
83177 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
83178 int iLevel, /* Which level of pWInfo->a[] should be coded */
83179 u8 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
83180 Bitmask notReady /* Which tables are currently available */
83181 ){
83182 int j, k; /* Loop counters */
83183 int iCur; /* The VDBE cursor for the table */
83184 int addrNxt; /* Where to jump to continue with the next IN case */
@@ -83190,24 +83864,22 @@
83190 Parse *pParse; /* Parsing context */
83191 Vdbe *v; /* The prepared stmt under constructions */
83192 struct SrcList_item *pTabItem; /* FROM clause term being coded */
83193 int addrBrk; /* Jump here to break out of the loop */
83194 int addrCont; /* Jump here to continue with next cycle */
83195 int regRowSet; /* Write rowids to this RowSet if non-negative */
83196 int codeRowSetEarly; /* True if index fully constrains the search */
83197
83198
83199 pParse = pWInfo->pParse;
83200 v = pParse->pVdbe;
83201 pWC = pWInfo->pWC;
83202 pLevel = &pWInfo->a[iLevel];
83203 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
83204 iCur = pTabItem->iCursor;
83205 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
83206 omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0;
83207 regRowSet = pWInfo->regRowSet;
83208 codeRowSetEarly = 0;
83209
83210 /* Create labels for the "break" and "continue" instructions
83211 ** for the current loop. Jump to addrBrk to break out of a loop.
83212 ** Jump to cont to go immediately to the next iteration of the
83213 ** loop.
@@ -83242,24 +83914,20 @@
83242 pVtabIdx->aConstraintUsage;
83243 const struct sqlite3_index_constraint *aConstraint =
83244 pVtabIdx->aConstraint;
83245
83246 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
83247 pParse->disableColCache++;
83248 for(j=1; j<=nConstraint; j++){
83249 for(k=0; k<nConstraint; k++){
83250 if( aUsage[k].argvIndex==j ){
83251 int iTerm = aConstraint[k].iTermOffset;
83252 assert( pParse->disableColCache );
83253 sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
83254 break;
83255 }
83256 }
83257 if( k==nConstraint ) break;
83258 }
83259 assert( pParse->disableColCache );
83260 pParse->disableColCache--;
83261 sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
83262 sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
83263 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
83264 pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
83265 pVtabIdx->needToFreeIdxStr = 0;
@@ -83270,15 +83938,10 @@
83270 }
83271 }
83272 pLevel->op = OP_VNext;
83273 pLevel->p1 = iCur;
83274 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
83275 codeRowSetEarly = regRowSet>=0 ? whereRowReadyForOutput(pWC) : 0;
83276 if( codeRowSetEarly ){
83277 sqlite3VdbeAddOp2(v, OP_VRowid, iCur, iReg);
83278 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, iReg);
83279 }
83280 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
83281 }else
83282 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83283
83284 if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
@@ -83285,26 +83948,21 @@
83285 /* Case 1: We can directly reference a single row using an
83286 ** equality comparison against the ROWID field. Or
83287 ** we reference multiple rows using a "rowid IN (...)"
83288 ** construct.
83289 */
83290 int r1;
83291 int rtmp = sqlite3GetTempReg(pParse);
83292 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
83293 assert( pTerm!=0 );
83294 assert( pTerm->pExpr!=0 );
83295 assert( pTerm->leftCursor==iCur );
83296 assert( omitTable==0 );
83297 r1 = codeEqualityTerm(pParse, pTerm, pLevel, rtmp);
83298 addrNxt = pLevel->addrNxt;
83299 sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, addrNxt);
83300 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, r1);
83301 codeRowSetEarly = (pWC->nTerm==1 && regRowSet>=0) ?1:0;
83302 if( codeRowSetEarly ){
83303 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
83304 }
83305 sqlite3ReleaseTempReg(pParse, rtmp);
83306 VdbeComment((v, "pk"));
83307 pLevel->op = OP_Noop;
83308 }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
83309 /* Case 2: We have an inequality comparison against the ROWID field.
83310 */
@@ -83367,22 +84025,16 @@
83367 start = sqlite3VdbeCurrentAddr(v);
83368 pLevel->op = bRev ? OP_Prev : OP_Next;
83369 pLevel->p1 = iCur;
83370 pLevel->p2 = start;
83371 pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
83372 codeRowSetEarly = regRowSet>=0 ? whereRowReadyForOutput(pWC) : 0;
83373 if( codeRowSetEarly || testOp!=OP_Noop ){
83374 int r1 = sqlite3GetTempReg(pParse);
83375 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
83376 if( testOp!=OP_Noop ){
83377 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, r1);
83378 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
83379 }
83380 if( codeRowSetEarly ){
83381 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
83382 }
83383 sqlite3ReleaseTempReg(pParse, r1);
83384 }
83385 }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
83386 /* Case 3: A scan using an index.
83387 **
83388 ** The WHERE clause may contain zero or more equality
@@ -83503,16 +84155,11 @@
83503 start_constraints = pRangeStart || nEq>0;
83504
83505 /* Seek the index cursor to the start of the range. */
83506 nConstraint = nEq;
83507 if( pRangeStart ){
83508 int dcc = pParse->disableColCache;
83509 if( pRangeEnd ){
83510 pParse->disableColCache++;
83511 }
83512 sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
83513 pParse->disableColCache = dcc;
83514 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
83515 nConstraint++;
83516 }else if( isMinQuery ){
83517 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
83518 nConstraint++;
@@ -83534,10 +84181,11 @@
83534 /* Load the value for the inequality constraint at the end of the
83535 ** range (if any).
83536 */
83537 nConstraint = nEq;
83538 if( pRangeEnd ){
 
83539 sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
83540 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
83541 codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
83542 nConstraint++;
83543 }
@@ -83565,24 +84213,21 @@
83565 testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
83566 if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
83567 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
83568 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
83569 }
 
83570
83571 /* Seek the table cursor, if required */
83572 disableTerm(pLevel, pRangeStart);
83573 disableTerm(pLevel, pRangeEnd);
83574 codeRowSetEarly = regRowSet>=0 ? whereRowReadyForOutput(pWC) : 0;
83575 if( !omitTable || codeRowSetEarly ){
83576 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1);
83577 if( codeRowSetEarly ){
83578 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
83579 }else{
83580 sqlite3VdbeAddOp2(v, OP_Seek, iCur, r1); /* Deferred seek */
83581 }
83582 }
83583 sqlite3ReleaseTempReg(pParse, r1);
83584
83585 /* Record the instruction used to terminate the loop. Disable
83586 ** WHERE clause terms made redundant by the index range scan.
83587 */
83588 pLevel->op = bRev ? OP_Prev : OP_Next;
@@ -83601,70 +84246,110 @@
83601 ** CREATE INDEX i3 ON t1(c);
83602 **
83603 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
83604 **
83605 ** In the example, there are three indexed terms connected by OR.
83606 ** The top of the loop is constructed by creating a RowSet object
83607 ** and populating it. Then looping over elements of the rowset.
83608 **
83609 ** Null 1
83610 ** # fill RowSet 1 with entries where a=5 using i1
83611 ** # fill Rowset 1 with entries where b=7 using i2
83612 ** # fill Rowset 1 with entries where c=11 and d=13 i3 and t1
83613 ** A: RowSetRead 1, B, 2
83614 ** Seek i, 2
83615 **
83616 ** The bottom of the loop looks like this:
83617 **
83618 ** Goto 0, A
83619 ** B:
83620 */
83621 int regOrRowset; /* Register holding the RowSet object */
83622 int regNextRowid; /* Register holding next rowid */
 
 
 
 
 
 
 
 
 
 
83623 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
83624 WhereTerm *pOrTerm; /* A single subterm within the OR-clause */
83625 SrcList oneTab; /* Shortened table list */
 
 
 
 
 
 
 
83626
83627 pTerm = pLevel->plan.u.pTerm;
83628 assert( pTerm!=0 );
83629 assert( pTerm->eOperator==WO_OR );
83630 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
83631 pOrWc = &pTerm->u.pOrInfo->wc;
83632 codeRowSetEarly = (regRowSet>=0 && pWC->nTerm==1) ?1:0;
83633
83634 if( codeRowSetEarly ){
83635 regOrRowset = regRowSet;
83636 }else{
83637 regOrRowset = sqlite3GetTempReg(pParse);
83638 sqlite3VdbeAddOp2(v, OP_Null, 0, regOrRowset);
83639 }
83640 oneTab.nSrc = 1;
83641 oneTab.nAlloc = 1;
83642 oneTab.a[0] = *pTabItem;
83643 for(j=0, pOrTerm=pOrWc->a; j<pOrWc->nTerm; j++, pOrTerm++){
83644 WhereInfo *pSubWInfo;
83645 if( pOrTerm->leftCursor!=iCur && pOrTerm->eOperator!=WO_AND ) continue;
83646 pSubWInfo = sqlite3WhereBegin(pParse, &oneTab, pOrTerm->pExpr, 0,
83647 WHERE_FILL_ROWSET | WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE,
83648 regOrRowset);
83649 if( pSubWInfo ){
83650 sqlite3WhereEnd(pSubWInfo);
83651 }
83652 }
83653 sqlite3VdbeResolveLabel(v, addrCont);
83654 if( !codeRowSetEarly ){
83655 regNextRowid = sqlite3GetTempReg(pParse);
83656 addrCont =
83657 sqlite3VdbeAddOp3(v, OP_RowSetRead, regOrRowset,addrBrk,regNextRowid);
83658 sqlite3VdbeAddOp2(v, OP_Seek, iCur, regNextRowid);
83659 sqlite3ReleaseTempReg(pParse, regNextRowid);
83660 /* sqlite3ReleaseTempReg(pParse, regOrRowset); // Preserve the RowSet */
83661 pLevel->op = OP_Goto;
83662 pLevel->p2 = addrCont;
83663 }else{
83664 pLevel->op = OP_Noop;
83665 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83666 disableTerm(pLevel, pTerm);
83667 }else
83668 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
83669
83670 {
@@ -83677,11 +84362,10 @@
83677 assert( omitTable==0 );
83678 pLevel->op = aStep[bRev];
83679 pLevel->p1 = iCur;
83680 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
83681 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
83682 codeRowSetEarly = 0;
83683 }
83684 notReady &= ~getMask(pWC->pMaskSet, iCur);
83685
83686 /* Insert code to test every subexpression that can be completely
83687 ** computed using the current set of tables.
@@ -83696,13 +84380,11 @@
83696 pE = pTerm->pExpr;
83697 assert( pE!=0 );
83698 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
83699 continue;
83700 }
83701 pParse->disableColCache += k;
83702 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
83703 pParse->disableColCache -= k;
83704 k = 1;
83705 pTerm->wtFlags |= TERM_CODED;
83706 }
83707
83708 /* For a LEFT OUTER JOIN, generate code that will record the fact that
@@ -83710,12 +84392,11 @@
83710 */
83711 if( pLevel->iLeftJoin ){
83712 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
83713 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
83714 VdbeComment((v, "record LEFT JOIN hit"));
83715 sqlite3ExprClearColumnCache(pParse, pLevel->iTabCur);
83716 sqlite3ExprClearColumnCache(pParse, pLevel->iIdxCur);
83717 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
83718 testcase( pTerm->wtFlags & TERM_VIRTUAL );
83719 testcase( pTerm->wtFlags & TERM_CODED );
83720 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
83721 if( (pTerm->prereqAll & notReady)!=0 ) continue;
@@ -83722,28 +84403,11 @@
83722 assert( pTerm->pExpr );
83723 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
83724 pTerm->wtFlags |= TERM_CODED;
83725 }
83726 }
83727
83728 /*
83729 ** If it was requested to store the results in a rowset and that has
83730 ** not already been do, then do so now.
83731 */
83732 if( regRowSet>=0 && !codeRowSetEarly ){
83733 int r1 = sqlite3GetTempReg(pParse);
83734 #ifndef SQLITE_OMIT_VIRTUALTABLE
83735 if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
83736 sqlite3VdbeAddOp2(v, OP_VRowid, iCur, r1);
83737 }else
83738 #endif
83739 {
83740 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
83741 }
83742 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, r1);
83743 sqlite3ReleaseTempReg(pParse, r1);
83744 }
83745
83746 return notReady;
83747 }
83748
83749 #if defined(SQLITE_TEST)
@@ -83766,11 +84430,11 @@
83766 if( pWInfo ){
83767 int i;
83768 for(i=0; i<pWInfo->nLevel; i++){
83769 sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
83770 if( pInfo ){
83771 assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed );
83772 if( pInfo->needToFreeIdxStr ){
83773 sqlite3_free(pInfo->idxStr);
83774 }
83775 sqlite3DbFree(db, pInfo);
83776 }
@@ -83872,12 +84536,11 @@
83872 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
83873 Parse *pParse, /* The parser context */
83874 SrcList *pTabList, /* A list of all tables to be scanned */
83875 Expr *pWhere, /* The WHERE clause */
83876 ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
83877 u8 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
83878 int regRowSet /* Register hold RowSet if WHERE_FILL_ROWSET is set */
83879 ){
83880 int i; /* Loop counter */
83881 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
83882 WhereInfo *pWInfo; /* Will become the return value of this function */
83883 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
@@ -83887,24 +84550,19 @@
83887 struct SrcList_item *pTabItem; /* A single entry from pTabList */
83888 WhereLevel *pLevel; /* A single level in the pWInfo list */
83889 int iFrom; /* First unused FROM clause element */
83890 int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */
83891 sqlite3 *db; /* Database connection */
83892 ExprList *pOrderBy = 0;
83893
83894 /* The number of tables in the FROM clause is limited by the number of
83895 ** bits in a Bitmask
83896 */
83897 if( pTabList->nSrc>BMS ){
83898 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
83899 return 0;
83900 }
83901
83902 if( ppOrderBy ){
83903 pOrderBy = *ppOrderBy;
83904 }
83905
83906 /* Allocate and initialize the WhereInfo structure that will become the
83907 ** return value. A single allocation is used to store the WhereInfo
83908 ** struct, the contents of WhereInfo.a[], the WhereClause structure
83909 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
83910 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
@@ -83922,11 +84580,10 @@
83922 }
83923 pWInfo->nLevel = pTabList->nSrc;
83924 pWInfo->pParse = pParse;
83925 pWInfo->pTabList = pTabList;
83926 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
83927 pWInfo->regRowSet = (wctrlFlags & WHERE_FILL_ROWSET) ? regRowSet : -1;
83928 pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
83929 pWInfo->wctrlFlags = wctrlFlags;
83930 pMaskSet = (WhereMaskSet*)&pWC[1];
83931
83932 /* Split the WHERE clause into separate subexpressions where each
@@ -84009,48 +84666,32 @@
84009 int once = 0; /* True when first table is seen */
84010
84011 memset(&bestPlan, 0, sizeof(bestPlan));
84012 bestPlan.rCost = SQLITE_BIG_DBL;
84013 for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
84014 int doNotReorder; /* True if this table should not be reordered */
84015 WhereCost sCost; /* Cost information from bestIndex() */
 
84016
84017 doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
84018 if( once && doNotReorder ) break;
84019 m = getMask(pMaskSet, pTabItem->iCursor);
84020 if( (m & notReady)==0 ){
84021 if( j==iFrom ) iFrom++;
84022 continue;
84023 }
 
 
84024 assert( pTabItem->pTab );
84025 #ifndef SQLITE_OMIT_VIRTUALTABLE
84026 if( IsVirtual(pTabItem->pTab) ){
84027 sqlite3_index_info *pVtabIdx; /* Current virtual index */
84028 sqlite3_index_info **ppIdxInfo = &pWInfo->a[j].pIdxInfo;
84029 sCost.rCost = bestVirtualIndex(pParse, pWC, pTabItem, notReady,
84030 ppOrderBy ? *ppOrderBy : 0, i==0,
84031 ppIdxInfo);
84032 sCost.plan.wsFlags = WHERE_VIRTUALTABLE;
84033 sCost.plan.u.pVtabIdx = pVtabIdx = *ppIdxInfo;
84034 if( pVtabIdx && pVtabIdx->orderByConsumed ){
84035 sCost.plan.wsFlags = WHERE_VIRTUALTABLE | WHERE_ORDERBY;
84036 }
84037 sCost.plan.nEq = 0;
84038 /* (double)2 In case of SQLITE_OMIT_FLOATING_POINT... */
84039 if( (SQLITE_BIG_DBL/((double)2))<sCost.rCost ){
84040 /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
84041 ** inital value of lowestCost in this loop. If it is, then
84042 ** the (cost<lowestCost) test below will never be true.
84043 */
84044 /* (double)2 In case of SQLITE_OMIT_FLOATING_POINT... */
84045 sCost.rCost = (SQLITE_BIG_DBL/((double)2));
84046 }
84047 }else
84048 #endif
84049 {
84050 bestIndex(pParse, pWC, pTabItem, notReady,
84051 (i==0 && ppOrderBy) ? *ppOrderBy : 0, &sCost);
84052 }
84053 if( once==0 || sCost.rCost<bestPlan.rCost ){
84054 once = 1;
84055 bestPlan = sCost;
84056 bestJ = j;
@@ -84091,11 +84732,11 @@
84091 assert( bestPlan.plan.u.pIdx==pIdx );
84092 }
84093 }
84094 }
84095 WHERETRACE(("*** Optimizer Finished ***\n"));
84096 if( db->mallocFailed ){
84097 goto whereBeginError;
84098 }
84099
84100 /* If the total query only selects a single row, then the ORDER BY
84101 ** clause is irrelevant.
@@ -84274,11 +84915,11 @@
84274 SrcList *pTabList = pWInfo->pTabList;
84275 sqlite3 *db = pParse->db;
84276
84277 /* Generate loop termination code.
84278 */
84279 sqlite3ExprClearColumnCache(pParse, -1);
84280 for(i=pTabList->nSrc-1; i>=0; i--){
84281 pLevel = &pWInfo->a[i];
84282 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
84283 if( pLevel->op!=OP_Noop ){
84284 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
@@ -84301,11 +84942,15 @@
84301 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
84302 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
84303 if( pLevel->iIdxCur>=0 ){
84304 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
84305 }
84306 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
 
 
 
 
84307 sqlite3VdbeJumpHere(v, addr);
84308 }
84309 }
84310
84311 /* The "break" point is here, just past the end of the outer loop.
@@ -86511,10 +87156,12 @@
86511 break;
86512 case 36: /* column ::= columnid type carglist */
86513 {
86514 yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
86515 yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
 
 
86516 }
86517 break;
86518 case 37: /* columnid ::= nm */
86519 {
86520 sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
@@ -87661,11 +88308,11 @@
87661 **
87662 ** This file contains C code that splits an SQL input string up into
87663 ** individual tokens and sends those tokens one-by-one over to the
87664 ** parser for analysis.
87665 **
87666 ** $Id: tokenize.c,v 1.155 2009/03/31 03:41:57 shane Exp $
87667 */
87668
87669 /*
87670 ** The charMap() macro maps alphabetic characters into their
87671 ** lower-case ASCII equivalent. On ASCII machines, this is just
@@ -88327,14 +88974,16 @@
88327 assert( pParse->nVarExpr==0 );
88328 assert( pParse->nVarExprAlloc==0 );
88329 assert( pParse->apVarExpr==0 );
88330 enableLookaside = db->lookaside.bEnabled;
88331 if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
 
88332 while( !db->mallocFailed && zSql[i]!=0 ){
88333 assert( i>=0 );
88334 pParse->sLastToken.z = (u8*)&zSql[i];
88335 assert( pParse->sLastToken.dyn==0 );
 
88336 pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
88337 i += pParse->sLastToken.n;
88338 if( i>mxSqlLen ){
88339 pParse->rc = SQLITE_TOOBIG;
88340 break;
@@ -88454,11 +89103,11 @@
88454 ** This file contains C code that implements the sqlite3_complete() API.
88455 ** This code used to be part of the tokenizer.c source file. But by
88456 ** separating it out, the code will be automatically omitted from
88457 ** static links that do not use it.
88458 **
88459 ** $Id: complete.c,v 1.7 2008/06/13 18:24:27 drh Exp $
88460 */
88461 #ifndef SQLITE_OMIT_COMPLETE
88462
88463 /*
88464 ** This is defined in tokenize.c. We just have to import the definition.
@@ -88549,11 +89198,11 @@
88549 static const u8 trans[7][8] = {
88550 /* Token: */
88551 /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
88552 /* 0 START: */ { 0, 0, 1, 2, 3, 1, 1, 1, },
88553 /* 1 NORMAL: */ { 0, 1, 1, 1, 1, 1, 1, 1, },
88554 /* 2 EXPLAIN: */ { 0, 2, 1, 1, 3, 1, 1, 1, },
88555 /* 3 CREATE: */ { 0, 3, 1, 1, 1, 3, 4, 1, },
88556 /* 4 TRIGGER: */ { 5, 4, 4, 4, 4, 4, 4, 4, },
88557 /* 5 SEMI: */ { 5, 5, 4, 4, 4, 4, 4, 6, },
88558 /* 6 END: */ { 0, 6, 4, 4, 4, 4, 4, 4, },
88559 };
@@ -88731,11 +89380,11 @@
88731 ** Main file for the SQLite library. The routines in this file
88732 ** implement the programmer interface to the library. Routines in
88733 ** other files are for internal use by SQLite and should not be
88734 ** accessed by users of the library.
88735 **
88736 ** $Id: main.c,v 1.536 2009/04/09 01:23:49 drh Exp $
88737 */
88738
88739 #ifdef SQLITE_ENABLE_FTS3
88740 /************** Include fts3.h in the middle of main.c ***********************/
88741 /************** Begin file fts3.h ********************************************/
@@ -88966,18 +89615,20 @@
88966 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
88967 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
88968 sqlite3GlobalConfig.inProgress = 1;
88969 memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
88970 sqlite3RegisterGlobalFunctions();
88971 rc = sqlite3_os_init();
88972 if( rc==SQLITE_OK ){
88973 rc = sqlite3PcacheInitialize();
 
 
88974 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
88975 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
 
88976 }
88977 sqlite3GlobalConfig.inProgress = 0;
88978 sqlite3GlobalConfig.isInit = (rc==SQLITE_OK ? 1 : 0);
88979 }
88980 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
88981
88982 /* Go back under the static mutex and clean up the recursive
88983 ** mutex to prevent a resource leak.
@@ -89015,22 +89666,24 @@
89015
89016 /*
89017 ** Undo the effects of sqlite3_initialize(). Must not be called while
89018 ** there are outstanding database connections or memory allocations or
89019 ** while any part of SQLite is otherwise in use in any thread. This
89020 ** routine is not threadsafe. Not by a long shot.
 
 
89021 */
89022 SQLITE_API int sqlite3_shutdown(void){
89023 sqlite3GlobalConfig.isMallocInit = 0;
89024 sqlite3PcacheShutdown();
89025 if( sqlite3GlobalConfig.isInit ){
 
 
89026 sqlite3_os_end();
 
 
 
 
89027 }
89028 sqlite3_reset_auto_extension();
89029 sqlite3MallocEnd();
89030 sqlite3MutexEnd();
89031 sqlite3GlobalConfig.isInit = 0;
89032 return SQLITE_OK;
89033 }
89034
89035 /*
89036 ** This API allows applications to modify the global configuration of
@@ -89538,41 +90191,45 @@
89538 /*
89539 ** Return a static string that describes the kind of error specified in the
89540 ** argument.
89541 */
89542 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
89543 const char *z;
89544 switch( rc & 0xff ){
89545 case SQLITE_ROW:
89546 case SQLITE_DONE:
89547 case SQLITE_OK: z = "not an error"; break;
89548 case SQLITE_ERROR: z = "SQL logic error or missing database"; break;
89549 case SQLITE_PERM: z = "access permission denied"; break;
89550 case SQLITE_ABORT: z = "callback requested query abort"; break;
89551 case SQLITE_BUSY: z = "database is locked"; break;
89552 case SQLITE_LOCKED: z = "database table is locked"; break;
89553 case SQLITE_NOMEM: z = "out of memory"; break;
89554 case SQLITE_READONLY: z = "attempt to write a readonly database"; break;
89555 case SQLITE_INTERRUPT: z = "interrupted"; break;
89556 case SQLITE_IOERR: z = "disk I/O error"; break;
89557 case SQLITE_CORRUPT: z = "database disk image is malformed"; break;
89558 case SQLITE_FULL: z = "database or disk is full"; break;
89559 case SQLITE_CANTOPEN: z = "unable to open database file"; break;
89560 case SQLITE_EMPTY: z = "table contains no data"; break;
89561 case SQLITE_SCHEMA: z = "database schema has changed"; break;
89562 case SQLITE_TOOBIG: z = "String or BLOB exceeded size limit"; break;
89563 case SQLITE_CONSTRAINT: z = "constraint failed"; break;
89564 case SQLITE_MISMATCH: z = "datatype mismatch"; break;
89565 case SQLITE_MISUSE: z = "library routine called out of sequence";break;
89566 case SQLITE_NOLFS: z = "large file support is disabled"; break;
89567 case SQLITE_AUTH: z = "authorization denied"; break;
89568 case SQLITE_FORMAT: z = "auxiliary database format error"; break;
89569 case SQLITE_RANGE: z = "bind or column index out of range"; break;
89570 case SQLITE_NOTADB: z = "file is encrypted or is not a database";break;
89571 default: z = "unknown error"; break;
89572 }
89573 return z;
 
 
 
 
89574 }
89575
89576 /*
89577 ** This routine implements a busy callback that sleeps and tries
89578 ** again until a timeout value is reached. The timeout value is
@@ -89726,11 +90383,11 @@
89726 if( zFunctionName==0 ||
89727 (xFunc && (xFinal || xStep)) ||
89728 (!xFunc && (xFinal && !xStep)) ||
89729 (!xFunc && (!xFinal && xStep)) ||
89730 (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
89731 (255<(nName = sqlite3Strlen(db, zFunctionName))) ){
89732 sqlite3Error(db, SQLITE_ERROR, "bad parameters");
89733 return SQLITE_ERROR;
89734 }
89735
89736 #ifndef SQLITE_OMIT_UTF16
@@ -89852,11 +90509,11 @@
89852 SQLITE_API int sqlite3_overload_function(
89853 sqlite3 *db,
89854 const char *zName,
89855 int nArg
89856 ){
89857 int nName = sqlite3Strlen(db, zName);
89858 int rc;
89859 sqlite3_mutex_enter(db->mutex);
89860 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
89861 sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
89862 0, sqlite3InvalidFunction, 0, 0);
@@ -89960,10 +90617,43 @@
89960 db->xRollbackCallback = xCallback;
89961 db->pRollbackArg = pArg;
89962 sqlite3_mutex_leave(db->mutex);
89963 return pRet;
89964 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89965
89966 /*
89967 ** This routine is called to create a connection to a database BTree
89968 ** driver. If zFilename is the name of a file, then that file is
89969 ** opened and used. If zFilename is the magic name ":memory:" then
@@ -89971,24 +90661,12 @@
89971 ** the connection is closed.) If zFilename is NULL then the database
89972 ** is a "virtual" database for transient use only and is deleted as
89973 ** soon as the connection is closed.
89974 **
89975 ** A virtual database can be either a disk file (that is automatically
89976 ** deleted when the file is closed) or it an be held entirely in memory,
89977 ** depending on the values of the SQLITE_TEMP_STORE compile-time macro and the
89978 ** db->temp_store variable, according to the following chart:
89979 **
89980 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
89981 ** ----------------- -------------- ------------------------------
89982 ** 0 any file
89983 ** 1 1 file
89984 ** 1 2 memory
89985 ** 1 0 file
89986 ** 2 1 file
89987 ** 2 2 memory
89988 ** 2 0 memory
89989 ** 3 any memory
89990 */
89991 SQLITE_PRIVATE int sqlite3BtreeFactory(
89992 const sqlite3 *db, /* Main database when opening aux otherwise 0 */
89993 const char *zFilename, /* Name of the file containing the BTree database */
89994 int omitJournal, /* if TRUE then do not journal this file */
@@ -90005,26 +90683,15 @@
90005 btFlags |= BTREE_OMIT_JOURNAL;
90006 }
90007 if( db->flags & SQLITE_NoReadlock ){
90008 btFlags |= BTREE_NO_READLOCK;
90009 }
90010 if( zFilename==0 ){
90011 #if SQLITE_TEMP_STORE==0
90012 /* Do nothing */
90013 #endif
90014 #ifndef SQLITE_OMIT_MEMORYDB
90015 #if SQLITE_TEMP_STORE==1
90016 if( db->temp_store==2 ) zFilename = ":memory:";
90017 #endif
90018 #if SQLITE_TEMP_STORE==2
90019 if( db->temp_store!=1 ) zFilename = ":memory:";
90020 #endif
90021 #if SQLITE_TEMP_STORE==3
90022 zFilename = ":memory:";
 
90023 #endif
90024 #endif /* SQLITE_OMIT_MEMORYDB */
90025 }
90026
90027 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
90028 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
90029 }
90030 rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
@@ -90156,23 +90823,25 @@
90156
90157 /* If SQLITE_UTF16 is specified as the encoding type, transform this
90158 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
90159 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
90160 */
90161 enc2 = enc & ~SQLITE_UTF16_ALIGNED;
90162 if( enc2==SQLITE_UTF16 ){
 
 
90163 enc2 = SQLITE_UTF16NATIVE;
90164 }
90165 if( (enc2&~3)!=0 ){
90166 return SQLITE_MISUSE;
90167 }
90168
90169 /* Check if this call is removing or replacing an existing collation
90170 ** sequence. If so, and there are active VMs, return busy. If there
90171 ** are no active VMs, invalidate any pre-compiled statements.
90172 */
90173 nName = sqlite3Strlen(db, zName);
90174 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 0);
90175 if( pColl && pColl->xCmp ){
90176 if( db->activeVdbeCnt ){
90177 sqlite3Error(db, SQLITE_BUSY,
90178 "unable to delete/modify collation sequence due to active statements");
@@ -90305,10 +90974,11 @@
90305 sqlite3 *db;
90306 int rc;
90307 CollSeq *pColl;
90308 int isThreadsafe;
90309
 
90310 #ifndef SQLITE_OMIT_AUTOINIT
90311 rc = sqlite3_initialize();
90312 if( rc ) return rc;
90313 #endif
90314
@@ -90364,13 +91034,13 @@
90364 #endif
90365 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
90366 | SQLITE_LoadExtension
90367 #endif
90368 ;
90369 sqlite3HashInit(&db->aCollSeq, 0);
90370 #ifndef SQLITE_OMIT_VIRTUALTABLE
90371 sqlite3HashInit(&db->aModule, 0);
90372 #endif
90373
90374 db->pVfs = sqlite3_vfs_find(zVfs);
90375 if( !db->pVfs ){
90376 rc = SQLITE_ERROR;
90377
--- 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.6.14. 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.
@@ -9,17 +9,17 @@
9 **
10 ** This file is all you need to compile SQLite. To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library. (If you do not have
13 ** the "sqlite3.h" header file at hand, you will find a copy in the first
14 ** 5533 lines past this header comment.) Additional code files may be
15 ** needed if you want a wrapper to interface SQLite with your choice of
16 ** programming language. The code for the "sqlite3" command-line shell
17 ** is also in a separate file. This file contains only code for the core
18 ** SQLite library.
19 **
20 ** This amalgamation was generated on 2009-05-07 00:36:11 UTC.
21 */
22 #define SQLITE_CORE 1
23 #define SQLITE_AMALGAMATION 1
24 #ifndef SQLITE_PRIVATE
25 # define SQLITE_PRIVATE static
@@ -39,11 +39,11 @@
39 ** May you share freely, never taking more than you give.
40 **
41 *************************************************************************
42 ** Internal interface definitions for SQLite.
43 **
44 ** @(#) $Id: sqliteInt.h,v 1.868 2009/05/04 11:42:30 danielk1977 Exp $
45 */
46 #ifndef _SQLITEINT_H_
47 #define _SQLITEINT_H_
48
49 /*
@@ -367,14 +367,14 @@
367 defined(SQLITE_POW2_MEMORY_SIZE)==0
368 # define SQLITE_SYSTEM_MALLOC 1
369 #endif
370
371 /*
372 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
373 ** sizes of memory allocations below this value where possible.
374 */
375 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
376 # define SQLITE_MALLOC_SOFT_LIMIT 1024
377 #endif
378
379 /*
380 ** We need to define _XOPEN_SOURCE as follows in order to enable
@@ -441,10 +441,24 @@
441 # define TESTONLY(X) X
442 #else
443 # define TESTONLY(X)
444 #endif
445
446 /*
447 ** Sometimes we need a small amount of code such as a variable initialization
448 ** to setup for a later assert() statement. We do not want this code to
449 ** appear when assert() is disabled. The following macro is therefore
450 ** used to contain that setup code. The "VVA" acronym stands for
451 ** "Verification, Validation, and Accreditation". In other words, the
452 ** code within VVA_ONLY() will only run during verification processes.
453 */
454 #ifndef NDEBUG
455 # define VVA_ONLY(X) X
456 #else
457 # define VVA_ONLY(X)
458 #endif
459
460 /*
461 ** The ALWAYS and NEVER macros surround boolean expressions which
462 ** are intended to always be true or false, respectively. Such
463 ** expressions could be omitted from the code completely. But they
464 ** are included in a few cases in order to enhance the resilience
@@ -482,24 +496,10 @@
496 #else
497 # define likely(X) !!(X)
498 # define unlikely(X) !!(X)
499 #endif
500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
501 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
502 /************** Begin file sqlite3.h *****************************************/
503 /*
504 ** 2001 September 15
505 **
@@ -530,11 +530,11 @@
530 ** The name of this file under configuration management is "sqlite.h.in".
531 ** The makefile makes some minor changes to this file (such as inserting
532 ** the version number) and changes its name to "sqlite3.h" as
533 ** part of the build process.
534 **
535 ** @(#) $Id: sqlite.h.in,v 1.447 2009/04/30 15:59:56 drh Exp $
536 */
537 #ifndef _SQLITE3_H_
538 #define _SQLITE3_H_
539 #include <stdarg.h> /* Needed for the definition of va_list */
540
@@ -599,12 +599,12 @@
599 **
600 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
601 **
602 ** Requirements: [H10011] [H10014]
603 */
604 #define SQLITE_VERSION "3.6.14"
605 #define SQLITE_VERSION_NUMBER 3006014
606
607 /*
608 ** CAPI3REF: Run-Time Library Version Numbers {H10020} <S60100>
609 ** KEYWORDS: sqlite3_version
610 **
@@ -1291,10 +1291,15 @@
1291 ** the process, or if it is the first time sqlite3_initialize() is invoked
1292 ** following a call to sqlite3_shutdown(). Only an effective call
1293 ** of sqlite3_initialize() does any initialization. All other calls
1294 ** are harmless no-ops.
1295 **
1296 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1297 ** call to sqlite3_shutdown() since the last sqlite3_initialize(). Only
1298 ** an effective call to sqlite3_shutdown() does any deinitialization.
1299 ** All other calls to sqlite3_shutdown() are harmless no-ops.
1300 **
1301 ** Among other things, sqlite3_initialize() shall invoke
1302 ** sqlite3_os_init(). Similarly, sqlite3_shutdown()
1303 ** shall invoke sqlite3_os_end().
1304 **
1305 ** The sqlite3_initialize() routine returns [SQLITE_OK] on success.
@@ -1717,19 +1722,23 @@
1722 ** on the [database connection] specified by the first parameter.
1723 ** Only changes that are directly specified by the [INSERT], [UPDATE],
1724 ** or [DELETE] statement are counted. Auxiliary changes caused by
1725 ** triggers are not counted. Use the [sqlite3_total_changes()] function
1726 ** to find the total number of changes including changes caused by triggers.
1727 **
1728 ** Changes to a view that are simulated by an [INSTEAD OF trigger]
1729 ** are not counted. Only real table changes are counted.
1730 **
1731 ** A "row change" is a change to a single row of a single table
1732 ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
1733 ** are changed as side effects of [REPLACE] constraint resolution,
1734 ** rollback, ABORT processing, [DROP TABLE], or by any other
1735 ** mechanisms do not count as direct row changes.
1736 **
1737 ** A "trigger context" is a scope of execution that begins and
1738 ** ends with the script of a [CREATE TRIGGER | trigger].
1739 ** Most SQL statements are
1740 ** evaluated outside of any trigger. This is the "top level"
1741 ** trigger context. If a trigger fires from the top level, a
1742 ** new trigger context is entered for the duration of that one
1743 ** trigger. Subtriggers create subcontexts for their duration.
1744 **
@@ -1747,20 +1756,12 @@
1756 ** changes in the most recently completed INSERT, UPDATE, or DELETE
1757 ** statement within the body of the same trigger.
1758 ** However, the number returned does not include changes
1759 ** caused by subtriggers since those have their own context.
1760 **
1761 ** See also the [sqlite3_total_changes()] interface and the
1762 ** [count_changes pragma].
 
 
 
 
 
 
 
 
1763 **
1764 ** Requirements:
1765 ** [H12241] [H12243]
1766 **
1767 ** If a separate thread makes changes on the same database connection
@@ -1770,31 +1771,25 @@
1771 SQLITE_API int sqlite3_changes(sqlite3*);
1772
1773 /*
1774 ** CAPI3REF: Total Number Of Rows Modified {H12260} <S10600>
1775 **
1776 ** This function returns the number of row changes caused by [INSERT],
1777 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
1778 ** The count includes all changes from all
1779 ** [CREATE TRIGGER | trigger] contexts. However,
1780 ** the count does not include changes used to implement [REPLACE] constraints,
1781 ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
1782 ** count does not rows of views that fire an [INSTEAD OF trigger], though if
1783 ** the INSTEAD OF trigger makes changes of its own, those changes are
1784 ** counted.
1785 ** The changes are counted as soon as the statement that makes them is
1786 ** completed (when the statement handle is passed to [sqlite3_reset()] or
1787 ** [sqlite3_finalize()]).
1788 **
1789 ** See also the [sqlite3_changes()] interface and the
1790 ** [count_changes pragma].
 
 
 
 
 
 
 
 
 
 
1791 **
1792 ** Requirements:
1793 ** [H12261] [H12263]
1794 **
1795 ** If a separate thread makes changes on the same database connection
@@ -1824,12 +1819,20 @@
1819 ** An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
1820 ** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
1821 ** that is inside an explicit transaction, then the entire transaction
1822 ** will be rolled back automatically.
1823 **
1824 ** The sqlite3_interrupt(D) call is in effect until all currently running
1825 ** SQL statements on [database connection] D complete. Any new SQL statements
1826 ** that are started after the sqlite3_interrupt() call and before the
1827 ** running statements reaches zero are interrupted as if they had been
1828 ** running prior to the sqlite3_interrupt() call. New SQL statements
1829 ** that are started after the running statement count reaches zero are
1830 ** not effected by the sqlite3_interrupt().
1831 ** A call to sqlite3_interrupt(D) that occurs when there are no running
1832 ** SQL statements is a no-op and has no effect on SQL statements
1833 ** that are started after the sqlite3_interrupt() call returns.
1834 **
1835 ** Requirements:
1836 ** [H12271] [H12272]
1837 **
1838 ** If the database connection closes while [sqlite3_interrupt()]
@@ -1838,23 +1841,33 @@
1841 SQLITE_API void sqlite3_interrupt(sqlite3*);
1842
1843 /*
1844 ** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} <S70200>
1845 **
1846 ** These routines are useful during command-line input to determine if the
1847 ** currently entered text seems to form a complete SQL statement or
1848 ** if additional input is needed before sending the text into
1849 ** SQLite for parsing. These routines return 1 if the input string
1850 ** appears to be a complete SQL statement. A statement is judged to be
1851 ** complete if it ends with a semicolon token and is not a prefix of a
1852 ** well-formed CREATE TRIGGER statement. Semicolons that are embedded within
1853 ** string literals or quoted identifier names or comments are not
1854 ** independent tokens (they are part of the token in which they are
1855 ** embedded) and thus do not count as a statement terminator. Whitespace
1856 ** and comments that follow the final semicolon are ignored.
1857 **
1858 ** These routines return 0 if the statement is incomplete. If a
1859 ** memory allocation fails, then SQLITE_NOMEM is returned.
1860 **
1861 ** These routines do not parse the SQL statements thus
1862 ** will not detect syntactically incorrect SQL.
1863 **
1864 ** If SQLite has not been initialized using [sqlite3_initialize()] prior
1865 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
1866 ** automatically by sqlite3_complete16(). If that initialization fails,
1867 ** then the return value from sqlite3_complete16() will be non-zero
1868 ** regardless of whether or not the input SQL is complete.
1869 **
1870 ** Requirements: [H10511] [H10512]
1871 **
1872 ** The input to [sqlite3_complete()] must be a zero-terminated
1873 ** UTF-8 string.
@@ -2279,25 +2292,30 @@
2292 **
2293 ** When the callback returns [SQLITE_OK], that means the operation
2294 ** requested is ok. When the callback returns [SQLITE_DENY], the
2295 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2296 ** authorizer will fail with an error message explaining that
2297 ** access is denied.
 
 
 
 
 
 
2298 **
2299 ** The first parameter to the authorizer callback is a copy of the third
2300 ** parameter to the sqlite3_set_authorizer() interface. The second parameter
2301 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2302 ** the particular action to be authorized. The third through sixth parameters
2303 ** to the callback are zero-terminated strings that contain additional
2304 ** details about the action to be authorized.
2305 **
2306 ** If the action code is [SQLITE_READ]
2307 ** and the callback returns [SQLITE_IGNORE] then the
2308 ** [prepared statement] statement is constructed to substitute
2309 ** a NULL value in place of the table column that would have
2310 ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
2311 ** return can be used to deny an untrusted user access to individual
2312 ** columns of a table.
2313 ** If the action code is [SQLITE_DELETE] and the callback returns
2314 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2315 ** [truncate optimization] is disabled and all rows are deleted individually.
2316 **
2317 ** An authorizer is used when [sqlite3_prepare | preparing]
2318 ** SQL statements from an untrusted source, to ensure that the SQL statements
2319 ** do not try to access data they are not allowed to see, or that they do not
2320 ** try to execute malicious statements that damage the database. For
2321 ** example, an application may allow a user to enter arbitrary
@@ -2327,11 +2345,13 @@
2345 ** schema change. Hence, the application should ensure that the
2346 ** correct authorizer callback remains in place during the [sqlite3_step()].
2347 **
2348 ** Note that the authorizer callback is invoked only during
2349 ** [sqlite3_prepare()] or its variants. Authorization is not
2350 ** performed during statement evaluation in [sqlite3_step()], unless
2351 ** as stated in the previous paragraph, sqlite3_step() invokes
2352 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2353 **
2354 ** Requirements:
2355 ** [H12501] [H12502] [H12503] [H12504] [H12505] [H12506] [H12507] [H12510]
2356 ** [H12511] [H12512] [H12520] [H12521] [H12522]
2357 */
@@ -3983,16 +4003,18 @@
4003 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4004 ** and a UTF-16 string for sqlite3_create_collation16(). In all cases
4005 ** the name is passed as the second function argument.
4006 **
4007 ** The third argument may be one of the constants [SQLITE_UTF8],
4008 ** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
4009 ** routine expects to be passed pointers to strings encoded using UTF-8,
4010 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. The
4011 ** third argument might also be [SQLITE_UTF16] to indicate that the routine
4012 ** expects pointers to be UTF-16 strings in the native byte order, or the
4013 ** argument can be [SQLITE_UTF16_ALIGNED] if the
4014 ** the routine expects pointers to 16-bit word aligned strings
4015 ** of UTF-16 in the native byte order.
4016 **
4017 ** A pointer to the user supplied routine must be passed as the fifth
4018 ** argument. If it is NULL, this is the same as deleting the collation
4019 ** sequence (so that SQLite cannot call it anymore).
4020 ** Each time the application supplied function is invoked, it is passed
@@ -4012,10 +4034,12 @@
4034 ** destroyed and is passed a copy of the fourth parameter void* pointer
4035 ** of the sqlite3_create_collation_v2().
4036 ** Collations are destroyed when they are overridden by later calls to the
4037 ** collation creation functions or when the [database connection] is closed
4038 ** using [sqlite3_close()].
4039 **
4040 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4041 **
4042 ** Requirements:
4043 ** [H16603] [H16604] [H16606] [H16609] [H16612] [H16615] [H16618] [H16621]
4044 ** [H16624] [H16627] [H16630]
4045 */
@@ -4566,19 +4590,24 @@
4590 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
4591 typedef struct sqlite3_module sqlite3_module;
4592
4593 /*
4594 ** CAPI3REF: Virtual Table Object {H18000} <S20400>
4595 ** KEYWORDS: sqlite3_module {virtual table module}
4596 ** EXPERIMENTAL
4597 **
4598 ** This structure, sometimes called a a "virtual table module",
4599 ** defines the implementation of a [virtual tables].
4600 ** This structure consists mostly of methods for the module.
4601 **
4602 ** A virtual table module is created by filling in a persistent
4603 ** instance of this structure and passing a pointer to that instance
4604 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
4605 ** The registration remains valid until it is replaced by a different
4606 ** module or until the [database connection] closes. The content
4607 ** of this structure must not change while it is registered with
4608 ** any database connection.
4609 */
4610 struct sqlite3_module {
4611 int iVersion;
4612 int (*xCreate)(sqlite3*, void *pAux,
4613 int argc, const char *const*argv,
@@ -4612,12 +4641,12 @@
4641 ** CAPI3REF: Virtual Table Indexing Information {H18100} <S20400>
4642 ** KEYWORDS: sqlite3_index_info
4643 ** EXPERIMENTAL
4644 **
4645 ** The sqlite3_index_info structure and its substructures is used to
4646 ** pass information into and receive the reply from the [xBestIndex]
4647 ** method of a [virtual table module]. The fields under **Inputs** are the
4648 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
4649 ** results into the **Outputs** fields.
4650 **
4651 ** The aConstraint[] array records WHERE clause constraints of the form:
4652 **
@@ -4636,31 +4665,30 @@
4665 ** form that refer to the particular virtual table being queried.
4666 **
4667 ** Information about the ORDER BY clause is stored in aOrderBy[].
4668 ** Each term of aOrderBy records a column of the ORDER BY clause.
4669 **
4670 ** The [xBestIndex] method must fill aConstraintUsage[] with information
4671 ** about what parameters to pass to xFilter. If argvIndex>0 then
4672 ** the right-hand side of the corresponding aConstraint[] is evaluated
4673 ** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit
4674 ** is true, then the constraint is assumed to be fully handled by the
4675 ** virtual table and is not checked again by SQLite.
4676 **
4677 ** The idxNum and idxPtr values are recorded and passed into the
4678 ** [xFilter] method.
4679 ** [sqlite3_free()] is used to free idxPtr if and only iff
4680 ** needToFreeIdxPtr is true.
4681 **
4682 ** The orderByConsumed means that output from [xFilter]/[xNext] will occur in
4683 ** the correct order to satisfy the ORDER BY clause so that no separate
4684 ** sorting step is required.
4685 **
4686 ** The estimatedCost value is an estimate of the cost of doing the
4687 ** particular lookup. A full scan of a table with N entries should have
4688 ** a cost of N. A binary search of a table of N entries should have a
4689 ** cost of approximately log(N).
 
 
 
4690 */
4691 struct sqlite3_index_info {
4692 /* Inputs */
4693 int nConstraint; /* Number of entries in aConstraint */
4694 struct sqlite3_index_constraint {
@@ -4694,64 +4722,69 @@
4722
4723 /*
4724 ** CAPI3REF: Register A Virtual Table Implementation {H18200} <S20400>
4725 ** EXPERIMENTAL
4726 **
4727 ** This routine is used to register a new [virtual table module] name.
4728 ** Module names must be registered before
4729 ** creating a new [virtual table] using the module, or before using a
4730 ** preexisting [virtual table] for the module.
4731 **
4732 ** The module name is registered on the [database connection] specified
4733 ** by the first parameter. The name of the module is given by the
4734 ** second parameter. The third parameter is a pointer to
4735 ** the implementation of the [virtual table module]. The fourth
4736 ** parameter is an arbitrary client data pointer that is passed through
4737 ** into the [xCreate] and [xConnect] methods of the virtual table module
4738 ** when a new virtual table is be being created or reinitialized.
4739 **
4740 ** This interface has exactly the same effect as calling
4741 ** [sqlite3_create_module_v2()] with a NULL client data destructor.
4742 */
4743 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
4744 sqlite3 *db, /* SQLite connection to register module with */
4745 const char *zName, /* Name of the module */
4746 const sqlite3_module *p, /* Methods for the module */
4747 void *pClientData /* Client data for xCreate/xConnect */
4748 );
4749
4750 /*
4751 ** CAPI3REF: Register A Virtual Table Implementation {H18210} <S20400>
4752 ** EXPERIMENTAL
4753 **
4754 ** This routine is identical to the [sqlite3_create_module()] method,
4755 ** except that it has an extra parameter to specify
4756 ** a destructor function for the client data pointer. SQLite will
4757 ** invoke the destructor function (if it is not NULL) when SQLite
4758 ** no longer needs the pClientData pointer.
4759 */
4760 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
4761 sqlite3 *db, /* SQLite connection to register module with */
4762 const char *zName, /* Name of the module */
4763 const sqlite3_module *p, /* Methods for the module */
4764 void *pClientData, /* Client data for xCreate/xConnect */
4765 void(*xDestroy)(void*) /* Module destructor function */
4766 );
4767
4768 /*
4769 ** CAPI3REF: Virtual Table Instance Object {H18010} <S20400>
4770 ** KEYWORDS: sqlite3_vtab
4771 ** EXPERIMENTAL
4772 **
4773 ** Every [virtual table module] implementation uses a subclass
4774 ** of the following structure to describe a particular instance
4775 ** of the [virtual table]. Each subclass will
4776 ** be tailored to the specific needs of the module implementation.
4777 ** The purpose of this superclass is to define certain fields that are
4778 ** common to all module implementations.
4779 **
4780 ** Virtual tables methods can set an error message by assigning a
4781 ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
4782 ** take care that any prior string is freed by a call to [sqlite3_free()]
4783 ** prior to assigning a new string to zErrMsg. After the error message
4784 ** is delivered up to the client application, the string will be automatically
4785 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
 
 
 
 
 
 
4786 */
4787 struct sqlite3_vtab {
4788 const sqlite3_module *pModule; /* The module for this virtual table */
4789 int nRef; /* Used internally */
4790 char *zErrMsg; /* Error message from sqlite3_mprintf() */
@@ -4758,24 +4791,25 @@
4791 /* Virtual table implementations will typically add additional fields */
4792 };
4793
4794 /*
4795 ** CAPI3REF: Virtual Table Cursor Object {H18020} <S20400>
4796 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
4797 ** EXPERIMENTAL
4798 **
4799 ** Every [virtual table module] implementation uses a subclass of the
4800 ** following structure to describe cursors that point into the
4801 ** [virtual table] and are used
4802 ** to loop through the virtual table. Cursors are created using the
4803 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
4804 ** by the [sqlite3_module.xClose | xClose] method. Cussors are used
4805 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
4806 ** of the module. Each module implementation will define
4807 ** the content of a cursor structure to suit its own needs.
4808 **
4809 ** This superclass exists in order to define fields of the cursor that
4810 ** are common to all implementations.
 
 
 
4811 */
4812 struct sqlite3_vtab_cursor {
4813 sqlite3_vtab *pVtab; /* Virtual table of this cursor */
4814 /* Virtual table implementations will typically add additional fields */
4815 };
@@ -4782,37 +4816,33 @@
4816
4817 /*
4818 ** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} <S20400>
4819 ** EXPERIMENTAL
4820 **
4821 ** The [xCreate] and [xConnect] methods of a
4822 ** [virtual table module] call this interface
4823 ** to declare the format (the names and datatypes of the columns) of
4824 ** the virtual tables they implement.
 
 
 
4825 */
4826 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
4827
4828 /*
4829 ** CAPI3REF: Overload A Function For A Virtual Table {H18300} <S20400>
4830 ** EXPERIMENTAL
4831 **
4832 ** Virtual tables can provide alternative implementations of functions
4833 ** using the [xFindFunction] method of the [virtual table module].
4834 ** But global versions of those functions
4835 ** must exist in order to be overloaded.
4836 **
4837 ** This API makes sure a global version of a function with a particular
4838 ** name and number of parameters exists. If no such function exists
4839 ** before this API is called, a new function is created. The implementation
4840 ** of the new function always causes an exception to be thrown. So
4841 ** the new function is not good for anything by itself. Its only
4842 ** purpose is to be a placeholder function that can be overloaded
4843 ** by a [virtual table].
 
 
 
4844 */
4845 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
4846
4847 /*
4848 ** The interface to the virtual-table mechanism defined above (back up
@@ -6020,11 +6050,11 @@
6050 **
6051 *************************************************************************
6052 ** This is the header file for the generic hash-table implemenation
6053 ** used in SQLite.
6054 **
6055 ** $Id: hash.h,v 1.15 2009/05/02 13:29:38 drh Exp $
6056 */
6057 #ifndef _SQLITE_HASH_H_
6058 #define _SQLITE_HASH_H_
6059
6060 /* Forward declarations of structures. */
@@ -6033,17 +6063,29 @@
6063
6064 /* A complete hash table is an instance of the following structure.
6065 ** The internals of this structure are intended to be opaque -- client
6066 ** code should not attempt to access or modify the fields of this structure
6067 ** directly. Change this structure only by using the routines below.
6068 ** However, some of the "procedures" and "functions" for modifying and
6069 ** accessing this structure are really macros, so we can't really make
6070 ** this structure opaque.
6071 **
6072 ** All elements of the hash table are on a single doubly-linked list.
6073 ** Hash.first points to the head of this list.
6074 **
6075 ** There are Hash.htsize buckets. Each bucket points to a spot in
6076 ** the global doubly-linked list. The contents of the bucket are the
6077 ** element pointed to plus the next _ht.count-1 elements in the list.
6078 **
6079 ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
6080 ** by a linear search of the global list. For small tables, the
6081 ** Hash.ht table is never allocated because if there are few elements
6082 ** in the table, it is faster to do a linear search than to manage
6083 ** the hash table.
6084 */
6085 struct Hash {
6086 unsigned int htsize; /* Number of buckets in the hash table */
 
6087 unsigned int count; /* Number of entries in this table */
6088 HashElem *first; /* The first element of the array */
6089 struct _ht { /* the hash table */
6090 int count; /* Number of entries with this hash */
6091 HashElem *chain; /* Pointer to first entry with this hash */
@@ -6055,22 +6097,21 @@
6097 **
6098 ** Again, this structure is intended to be opaque, but it can't really
6099 ** be opaque because it is used by macros.
6100 */
6101 struct HashElem {
6102 HashElem *next, *prev; /* Next and previous elements in the table */
6103 void *data; /* Data associated with this element */
6104 const char *pKey; int nKey; /* Key associated with this element */
6105 };
6106
6107 /*
6108 ** Access routines. To delete, insert a NULL pointer.
6109 */
6110 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
6111 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
6112 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
 
6113 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6114
6115 /*
6116 ** Macros for looping over all elements of a hash table. The idiom is
6117 ** like this:
@@ -6084,17 +6125,17 @@
6125 ** }
6126 */
6127 #define sqliteHashFirst(H) ((H)->first)
6128 #define sqliteHashNext(E) ((E)->next)
6129 #define sqliteHashData(E) ((E)->data)
6130 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
6131 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
6132
6133 /*
6134 ** Number of entries in a hash table
6135 */
6136 /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
6137
6138 #endif /* _SQLITE_HASH_H_ */
6139
6140 /************** End of hash.h ************************************************/
6141 /************** Continuing where we left off in sqliteInt.h ******************/
@@ -6592,11 +6633,11 @@
6633 *************************************************************************
6634 ** This header file defines the interface that the sqlite B-Tree file
6635 ** subsystem. See comments in the source code for a detailed description
6636 ** of what each interface routine does.
6637 **
6638 ** @(#) $Id: btree.h,v 1.114 2009/05/04 11:42:30 danielk1977 Exp $
6639 */
6640 #ifndef _BTREE_H_
6641 #define _BTREE_H_
6642
6643 /* TODO: This definition is just included so other modules compile. It
@@ -6727,11 +6768,11 @@
6768 );
6769 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
6770 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
6771 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
6772 const void *pData, int nData,
6773 int nZero, int bias, int seekResult);
6774 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
6775 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
6776 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
6777 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
6778 SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor*);
@@ -6973,110 +7014,110 @@
7014 #define OP_OpenWrite 10
7015 #define OP_NotNull 72 /* same as TK_NOTNULL */
7016 #define OP_If 11
7017 #define OP_ToInt 144 /* same as TK_TO_INT */
7018 #define OP_String8 94 /* same as TK_STRING */
7019 #define OP_CollSeq 12
7020 #define OP_OpenRead 13
7021 #define OP_Expire 14
7022 #define OP_AutoCommit 15
 
7023 #define OP_Gt 75 /* same as TK_GT */
7024 #define OP_Pagecount 16
7025 #define OP_IntegrityCk 17
7026 #define OP_Sort 18
7027 #define OP_Copy 20
7028 #define OP_Trace 21
7029 #define OP_Function 22
7030 #define OP_IfNeg 23
7031 #define OP_And 67 /* same as TK_AND */
7032 #define OP_Subtract 85 /* same as TK_MINUS */
7033 #define OP_Noop 24
7034 #define OP_Return 25
7035 #define OP_Remainder 88 /* same as TK_REM */
7036 #define OP_NewRowid 26
7037 #define OP_Multiply 86 /* same as TK_STAR */
7038 #define OP_Variable 27
7039 #define OP_String 28
7040 #define OP_RealAffinity 29
7041 #define OP_VRename 30
7042 #define OP_ParseSchema 31
7043 #define OP_VOpen 32
7044 #define OP_Close 33
7045 #define OP_CreateIndex 34
7046 #define OP_IsUnique 35
7047 #define OP_NotFound 36
7048 #define OP_Int64 37
7049 #define OP_MustBeInt 38
7050 #define OP_Halt 39
7051 #define OP_Rowid 40
7052 #define OP_IdxLT 41
7053 #define OP_AddImm 42
7054 #define OP_Statement 43
7055 #define OP_RowData 44
7056 #define OP_MemMax 45
7057 #define OP_Or 66 /* same as TK_OR */
7058 #define OP_NotExists 46
7059 #define OP_Gosub 47
7060 #define OP_Divide 87 /* same as TK_SLASH */
7061 #define OP_Integer 48
7062 #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
7063 #define OP_Prev 49
7064 #define OP_RowSetRead 50
7065 #define OP_Concat 89 /* same as TK_CONCAT */
7066 #define OP_RowSetAdd 51
7067 #define OP_BitAnd 80 /* same as TK_BITAND */
7068 #define OP_VColumn 52
7069 #define OP_CreateTable 53
7070 #define OP_Last 54
7071 #define OP_SeekLe 55
7072 #define OP_IsNull 71 /* same as TK_ISNULL */
7073 #define OP_IncrVacuum 56
7074 #define OP_IdxRowid 57
7075 #define OP_ShiftRight 83 /* same as TK_RSHIFT */
7076 #define OP_ResetCount 58
7077 #define OP_ContextPush 59
7078 #define OP_Yield 60
7079 #define OP_DropTrigger 61
7080 #define OP_DropIndex 62
7081 #define OP_IdxGE 63
7082 #define OP_IdxDelete 64
7083 #define OP_Vacuum 65
7084 #define OP_IfNot 68
7085 #define OP_DropTable 69
7086 #define OP_SeekLt 70
7087 #define OP_MakeRecord 79
7088 #define OP_ToBlob 142 /* same as TK_TO_BLOB */
7089 #define OP_ResultRow 90
7090 #define OP_Delete 91
7091 #define OP_AggFinal 92
7092 #define OP_Compare 95
7093 #define OP_ShiftLeft 82 /* same as TK_LSHIFT */
7094 #define OP_Goto 96
7095 #define OP_TableLock 97
7096 #define OP_Clear 98
7097 #define OP_Le 76 /* same as TK_LE */
7098 #define OP_VerifyCookie 99
7099 #define OP_AggStep 100
7100 #define OP_ToText 141 /* same as TK_TO_TEXT */
7101 #define OP_Not 19 /* same as TK_NOT */
7102 #define OP_ToReal 145 /* same as TK_TO_REAL */
7103 #define OP_SetNumColumns 101
7104 #define OP_Transaction 102
7105 #define OP_VFilter 103
7106 #define OP_Ne 73 /* same as TK_NE */
7107 #define OP_VDestroy 104
7108 #define OP_ContextPop 105
7109 #define OP_BitOr 81 /* same as TK_BITOR */
7110 #define OP_Next 106
7111 #define OP_Count 107
7112 #define OP_IdxInsert 108
7113 #define OP_Lt 77 /* same as TK_LT */
7114 #define OP_SeekGe 109
7115 #define OP_Insert 110
7116 #define OP_Destroy 111
7117 #define OP_ReadCookie 112
7118 #define OP_RowSetTest 113
7119 #define OP_LoadAnalysis 114
7120 #define OP_Explain 115
7121 #define OP_HaltIfNull 116
7122 #define OP_OpenPseudo 117
7123 #define OP_OpenEphemeral 118
@@ -7117,24 +7158,24 @@
7158 #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
7159 #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
7160 #define OPFLG_OUT3 0x0020 /* out3: P3 is an output */
7161 #define OPFLG_INITIALIZER {\
7162 /* 0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x08, 0x02, 0x00,\
7163 /* 8 */ 0x00, 0x04, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00,\
7164 /* 16 */ 0x02, 0x00, 0x01, 0x04, 0x04, 0x00, 0x00, 0x05,\
7165 /* 24 */ 0x00, 0x04, 0x02, 0x00, 0x02, 0x04, 0x00, 0x00,\
7166 /* 32 */ 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05, 0x00,\
7167 /* 40 */ 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11, 0x01,\
7168 /* 48 */ 0x02, 0x01, 0x21, 0x08, 0x00, 0x02, 0x01, 0x11,\
7169 /* 56 */ 0x01, 0x02, 0x00, 0x00, 0x04, 0x00, 0x00, 0x11,\
7170 /* 64 */ 0x00, 0x00, 0x2c, 0x2c, 0x05, 0x00, 0x11, 0x05,\
7171 /* 72 */ 0x05, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x00,\
7172 /* 80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c,\
7173 /* 88 */ 0x2c, 0x2c, 0x00, 0x00, 0x00, 0x04, 0x02, 0x00,\
7174 /* 96 */ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,\
7175 /* 104 */ 0x00, 0x00, 0x01, 0x02, 0x08, 0x11, 0x00, 0x02,\
7176 /* 112 */ 0x02, 0x15, 0x00, 0x00, 0x10, 0x00, 0x00, 0x02,\
7177 /* 120 */ 0x00, 0x02, 0x01, 0x11, 0x00, 0x00, 0x05, 0x00,\
7178 /* 128 */ 0x11, 0x05, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00,\
7179 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
7180 /* 144 */ 0x04, 0x04,}
7181
@@ -7216,11 +7257,11 @@
7257 *************************************************************************
7258 ** This header file defines the interface that the sqlite page cache
7259 ** subsystem. The page cache subsystem reads and writes a file a page
7260 ** at a time and provides a journal for rollback.
7261 **
7262 ** @(#) $Id: pager.h,v 1.101 2009/04/30 09:10:38 danielk1977 Exp $
7263 */
7264
7265 #ifndef _PAGER_H_
7266 #define _PAGER_H_
7267
@@ -7322,11 +7363,11 @@
7363 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
7364 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
7365
7366 /* Functions used to manage pager transactions and savepoints. */
7367 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
7368 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
7369 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
7370 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7371 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7372 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7373 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
@@ -7917,11 +7958,10 @@
7958 struct Schema {
7959 int schema_cookie; /* Database schema version number for this file */
7960 Hash tblHash; /* All tables indexed by name */
7961 Hash idxHash; /* All (named) indices indexed by name */
7962 Hash trigHash; /* All triggers indexed by name */
 
7963 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
7964 u8 file_format; /* Schema format version for this file */
7965 u8 enc; /* Text encoding used by this database */
7966 u16 flags; /* Flags associated with this schema */
7967 int cache_size; /* Number of pages to use in the cache */
@@ -8473,32 +8513,25 @@
8513 **
8514 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
8515 **
8516 ** Each REFERENCES clause generates an instance of the following structure
8517 ** which is attached to the from-table. The to-table need not exist when
8518 ** the from-table is created. The existence of the to-table is not checked.
 
 
 
 
 
 
8519 */
8520 struct FKey {
8521 Table *pFrom; /* The table that contains the REFERENCES clause */
8522 FKey *pNextFrom; /* Next foreign key in pFrom */
8523 char *zTo; /* Name of table that the key points to */
 
8524 int nCol; /* Number of columns in this key */
 
 
 
 
8525 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
8526 u8 updateConf; /* How to resolve conflicts that occur on UPDATE */
8527 u8 deleteConf; /* How to resolve conflicts that occur on DELETE */
8528 u8 insertConf; /* How to resolve conflicts that occur on INSERT */
8529 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
8530 int iFrom; /* Index of column in pFrom */
8531 char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
8532 } aCol[1]; /* One entry for each of nCol column s */
8533 };
8534
8535 /*
8536 ** SQLite supports many different ways to resolve a constraint
8537 ** error. ROLLBACK processing means that a constraint violation
@@ -8568,10 +8601,11 @@
8601 */
8602 struct UnpackedRecord {
8603 KeyInfo *pKeyInfo; /* Collation and sort-order information */
8604 u16 nField; /* Number of entries in apMem[] */
8605 u16 flags; /* Boolean settings. UNPACKED_... below */
8606 i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
8607 Mem *aMem; /* Values */
8608 };
8609
8610 /*
8611 ** Allowed values of UnpackedRecord.flags
@@ -8579,10 +8613,11 @@
8613 #define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */
8614 #define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */
8615 #define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */
8616 #define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */
8617 #define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */
8618 #define UNPACKED_PREFIX_SEARCH 0x0020 /* A prefix match is considered OK */
8619
8620 /*
8621 ** Each SQL index is represented in memory by an
8622 ** instance of the following structure.
8623 **
@@ -8632,12 +8667,13 @@
8667 ** may contain random values. Do not make any assumptions about Token.dyn
8668 ** and Token.n when Token.z==0.
8669 */
8670 struct Token {
8671 const unsigned char *z; /* Text of the token. Not NULL-terminated! */
8672 unsigned dyn : 1; /* True for malloced memory, false for static */
8673 unsigned quoted : 1; /* True if token still has its quotes */
8674 unsigned n : 30; /* Number of characters in this token */
8675 };
8676
8677 /*
8678 ** An instance of this structure contains information needed to generate
8679 ** code for a SELECT that contains aggregate functions.
@@ -8795,11 +8831,11 @@
8831 #define EP_Agg 0x0002 /* Contains one or more aggregate functions */
8832 #define EP_Resolved 0x0004 /* IDs have been resolved to COLUMNs */
8833 #define EP_Error 0x0008 /* Expression contains one or more errors */
8834 #define EP_Distinct 0x0010 /* Aggregate function with DISTINCT keyword */
8835 #define EP_VarSelect 0x0020 /* pSelect is correlated, not constant */
8836 #define EP_DblQuoted 0x0040 /* token.z was originally in "..." */
8837 #define EP_InfixFunc 0x0080 /* True for an infix function: LIKE, GLOB, etc */
8838 #define EP_ExpCollate 0x0100 /* Collating sequence specified explicitly */
8839 #define EP_AnyAff 0x0200 /* Can take a cached column of any affinity */
8840 #define EP_FixedDest 0x0400 /* Result needed in a specific register */
8841 #define EP_IntValue 0x0800 /* Integer value contained in iTable */
@@ -9020,19 +9056,21 @@
9056 */
9057 sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
9058 };
9059
9060 /*
9061 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
9062 ** and the WhereInfo.wctrlFlags member.
9063 */
9064 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
9065 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
9066 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
9067 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
9068 #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
9069 #define WHERE_OMIT_OPEN 0x0010 /* Table cursor are already open */
9070 #define WHERE_OMIT_CLOSE 0x0020 /* Omit close of table & index cursors */
9071 #define WHERE_FORCE_TABLE 0x0040 /* Do not use an index-only search */
9072
9073 /*
9074 ** The WHERE clause processing routine has two halves. The
9075 ** first part does the start of the WHERE loop and the second
9076 ** half does the tail of the WHERE loop. An instance of
@@ -9041,11 +9079,10 @@
9079 */
9080 struct WhereInfo {
9081 Parse *pParse; /* Parsing and code generating context */
9082 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
9083 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE or DELETE */
 
9084 SrcList *pTabList; /* List of tables in the join */
9085 int iTop; /* The very beginning of the WHERE loop */
9086 int iContinue; /* Jump here to continue with next record */
9087 int iBreak; /* Jump here to break out of the loop */
9088 int nLevel; /* Number of nested loop */
@@ -9169,10 +9206,17 @@
9206 int iParm; /* A parameter used by the eDest disposal method */
9207 int iMem; /* Base register where results are written */
9208 int nMem; /* Number of registers allocated */
9209 };
9210
9211 /*
9212 ** Size of the column cache
9213 */
9214 #ifndef SQLITE_N_COLCACHE
9215 # define SQLITE_N_COLCACHE 10
9216 #endif
9217
9218 /*
9219 ** An SQL parser context. A copy of this structure is passed through
9220 ** the parser and down into all the parser action routine in order to
9221 ** carry around information that is global to the entire parse.
9222 **
@@ -9205,19 +9249,23 @@
9249 int nErr; /* Number of errors seen */
9250 int nTab; /* Number of previously allocated VDBE cursors */
9251 int nMem; /* Number of memory cells used so far */
9252 int nSet; /* Number of sets used so far */
9253 int ckBase; /* Base register of data during check constraints */
9254 int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
9255 int iCacheCnt; /* Counter used to generate aColCache[].lru values */
9256 u8 nColCache; /* Number of entries in the column cache */
9257 u8 iColCache; /* Next entry of the cache to replace */
9258 struct yColCache {
9259 int iTable; /* Table cursor number */
9260 int iColumn; /* Table column number */
9261 u8 affChange; /* True if this register has had an affinity change */
9262 u8 tempReg; /* iReg is a temp register that needs to be freed */
9263 int iLevel; /* Nesting level */
9264 int iReg; /* Reg with value of this column. 0 means none. */
9265 int lru; /* Least recently used entry has the smallest value */
9266 } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
9267 u32 writeMask; /* Start a write transaction on these databases */
9268 u32 cookieMask; /* Bitmask of schema verified databases */
9269 int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
9270 int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
9271 #ifndef SQLITE_OMIT_SHARED_CACHE
@@ -9271,16 +9319,17 @@
9319 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
9320 Parse *pParse; /* The Parse structure */
9321 };
9322
9323 /*
9324 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
9325 */
9326 #define OPFLAG_NCHANGE 1 /* Set to update db->nChange */
9327 #define OPFLAG_LASTROWID 2 /* Set to update db->lastRowid */
9328 #define OPFLAG_ISUPDATE 4 /* This OP_Insert is an sql UPDATE */
9329 #define OPFLAG_APPEND 8 /* This is likely to be an append */
9330 #define OPFLAG_USESEEKRESULT 16 /* Try to avoid a seek in BtreeInsert() */
9331
9332 /*
9333 * Each trigger present in the database schema is stored as an instance of
9334 * struct Trigger.
9335 *
@@ -9567,11 +9616,10 @@
9616 ** Internal function prototypes
9617 */
9618 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
9619 SQLITE_PRIVATE int sqlite3StrNICmp(const char *, const char *, int);
9620 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
 
9621 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
9622
9623 SQLITE_PRIVATE int sqlite3MallocInit(void);
9624 SQLITE_PRIVATE void sqlite3MallocEnd(void);
9625 SQLITE_PRIVATE void *sqlite3Malloc(int);
@@ -9626,12 +9674,11 @@
9674 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
9675 #endif
9676 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
9677 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
9678 SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
9679 SQLITE_PRIVATE int sqlite3Dequote(char*);
 
9680 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
9681 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
9682 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
9683 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
9684 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
@@ -9675,10 +9722,11 @@
9722 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
9723
9724 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
9725 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
9726 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
9727 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
9728 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
9729
9730 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
9731
9732 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
@@ -9716,18 +9764,21 @@
9764 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
9765 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
9766 #endif
9767 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
9768 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
9769 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
9770 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
9771 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, int);
9772 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
9773 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
9774 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
9775 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
9776 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
9777 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int);
9778 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
9779 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
 
9780 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
9781 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
9782 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
9783 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
9784 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
@@ -9765,12 +9816,12 @@
9816 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
9817 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int);
9818 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
9819 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
9820 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
9821 int*,int,int,int,int,int*);
9822 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int,int,int);
9823 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
9824 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
9825 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
9826 SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3*,Token*,const Token*);
9827 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
@@ -10027,10 +10078,12 @@
10078 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10079 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
10080 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10081 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10082 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10083 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
10084
10085
10086
10087 /*
10088 ** Available fault injectors. Should be numbered beginning with 0.
10089 */
@@ -10449,11 +10502,11 @@
10502 **
10503 ** There is only one exported symbol in this file - the function
10504 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
10505 ** All other code has file scope.
10506 **
10507 ** $Id: date.c,v 1.107 2009/05/03 20:23:53 drh Exp $
10508 **
10509 ** SQLite processes all times and dates as Julian Day numbers. The
10510 ** dates and times are stored as the number of days since noon
10511 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
10512 ** calendar system.
@@ -10774,18 +10827,19 @@
10827 static int parseDateOrTime(
10828 sqlite3_context *context,
10829 const char *zDate,
10830 DateTime *p
10831 ){
10832 int isRealNum; /* Return from sqlite3IsNumber(). Not used */
10833 if( parseYyyyMmDd(zDate,p)==0 ){
10834 return 0;
10835 }else if( parseHhMmSs(zDate, p)==0 ){
10836 return 0;
10837 }else if( sqlite3StrICmp(zDate,"now")==0){
10838 setDateTimeToCurrent(context, p);
10839 return 0;
10840 }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
10841 double r;
10842 getValue(zDate, &r);
10843 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
10844 p->validJD = 1;
10845 return 0;
@@ -10979,11 +11033,11 @@
11033 **
11034 ** Treat the current value of p->iJD as the number of
11035 ** seconds since 1970. Convert to a real julian day number.
11036 */
11037 if( strcmp(z, "unixepoch")==0 && p->validJD ){
11038 p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
11039 clearYMD_HMS_TZ(p);
11040 rc = 0;
11041 }
11042 #ifndef SQLITE_OMIT_LOCALTIME
11043 else if( strcmp(z, "utc")==0 ){
@@ -14965,11 +15019,11 @@
15019 **
15020 *************************************************************************
15021 **
15022 ** Memory allocation functions used throughout sqlite.
15023 **
15024 ** $Id: malloc.c,v 1.62 2009/05/03 20:23:54 drh Exp $
15025 */
15026
15027 /*
15028 ** This routine runs when the memory allocator sees that the
15029 ** total memory allocation is about to exceed the soft heap
@@ -15602,11 +15656,11 @@
15656 char *zNew;
15657 size_t n;
15658 if( z==0 ){
15659 return 0;
15660 }
15661 n = sqlite3Strlen30(z) + 1;
15662 assert( (n&0x7fffffff)==n );
15663 zNew = sqlite3DbMallocRaw(db, (int)n);
15664 if( zNew ){
15665 memcpy(zNew, z, n);
15666 }
@@ -15677,11 +15731,11 @@
15731 ** the public domain. The original comments are included here for
15732 ** completeness. They are very out-of-date but might be useful as
15733 ** an historical reference. Most of the "enhancements" have been backed
15734 ** out so that the functionality is now the same as standard printf().
15735 **
15736 ** $Id: printf.c,v 1.103 2009/05/04 20:20:16 drh Exp $
15737 **
15738 **************************************************************************
15739 **
15740 ** The following modules is an enhanced replacement for the "printf" subroutines
15741 ** found in the standard C library. The following enhancements are
@@ -16062,13 +16116,17 @@
16116 /* Fall through into the next case */
16117 case etORDINAL:
16118 case etRADIX:
16119 if( infop->flags & FLAG_SIGNED ){
16120 i64 v;
16121 if( flag_longlong ){
16122 v = va_arg(ap,i64);
16123 }else if( flag_long ){
16124 v = va_arg(ap,long int);
16125 }else{
16126 v = va_arg(ap,int);
16127 }
16128 if( v<0 ){
16129 longvalue = -v;
16130 prefix = '-';
16131 }else{
16132 longvalue = v;
@@ -16075,13 +16133,17 @@
16133 if( flag_plussign ) prefix = '+';
16134 else if( flag_blanksign ) prefix = ' ';
16135 else prefix = 0;
16136 }
16137 }else{
16138 if( flag_longlong ){
16139 longvalue = va_arg(ap,u64);
16140 }else if( flag_long ){
16141 longvalue = va_arg(ap,unsigned long int);
16142 }else{
16143 longvalue = va_arg(ap,unsigned int);
16144 }
16145 prefix = 0;
16146 }
16147 if( longvalue==0 ) flag_alternateform = 0;
16148 if( flag_zeropad && precision<width-(prefix!=0) ){
16149 precision = width-(prefix!=0);
@@ -16824,11 +16886,11 @@
16886 ** VDBE. This information used to all be at the top of the single
16887 ** source code file "vdbe.c". When that file became too big (over
16888 ** 6000 lines long) it was split up into several smaller files and
16889 ** this header information was factored out.
16890 **
16891 ** $Id: vdbeInt.h,v 1.170 2009/05/04 11:42:30 danielk1977 Exp $
16892 */
16893 #ifndef _VDBEINT_H_
16894 #define _VDBEINT_H_
16895
16896 /*
@@ -16888,10 +16950,14 @@
16950 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
16951 int nField; /* Number of fields in the header */
16952 i64 seqCount; /* Sequence counter */
16953 sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
16954 const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
16955
16956 /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
16957 ** OP_IsUnique opcode on this cursor. */
16958 int seekResult;
16959
16960 /* Cached information about the header for the data record that the
16961 ** cursor is currently pointing to. Only valid if cacheValid is true.
16962 ** aRow might point to (ephemeral) data for the current row, or it might
16963 ** be NULL.
@@ -17732,12 +17798,15 @@
17798 ** Utility functions used throughout sqlite.
17799 **
17800 ** This file contains functions for allocating memory, comparing
17801 ** strings, and stuff like that.
17802 **
17803 ** $Id: util.c,v 1.254 2009/05/06 19:03:14 drh Exp $
17804 */
17805 #ifdef SQLITE_HAVE_ISNAN
17806 # include <math.h>
17807 #endif
17808
17809 /*
17810 ** Routine needed to support the testcase() macro.
17811 */
17812 #ifdef SQLITE_COVERAGE_TEST
@@ -17768,13 +17837,24 @@
17837 }
17838 #endif
17839
17840 /*
17841 ** Return true if the floating point value is Not a Number (NaN).
17842 **
17843 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
17844 ** Otherwise, we have our own implementation that works on most systems.
17845 */
17846 SQLITE_PRIVATE int sqlite3IsNaN(double x){
17847 int rc; /* The value return */
17848 #if !defined(SQLITE_HAVE_ISNAN)
17849 /*
17850 ** Systems that support the isnan() library function should probably
17851 ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
17852 ** found that many systems do not have a working isnan() function so
17853 ** this implementation is provided as an alternative.
17854 **
17855 ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
17856 ** On the other hand, the use of -ffast-math comes with the following
17857 ** warning:
17858 **
17859 ** This option [-ffast-math] should never be turned on by any
17860 ** -O option since it can result in incorrect output for programs
@@ -17792,41 +17872,32 @@
17872 #ifdef __FAST_MATH__
17873 # error SQLite will not work correctly with the -ffast-math option of GCC.
17874 #endif
17875 volatile double y = x;
17876 volatile double z = y;
17877 rc = (y!=z);
17878 #else /* if defined(SQLITE_HAVE_ISNAN) */
17879 rc = isnan(x);
17880 #endif /* SQLITE_HAVE_ISNAN */
17881 testcase( rc );
17882 return rc;
17883 }
17884
17885 /*
17886 ** Compute a string length that is limited to what can be stored in
17887 ** lower 30 bits of a 32-bit signed integer.
17888 **
17889 ** The value returned will never be negative. Nor will it ever be greater
17890 ** than the actual length of the string. For very long strings (greater
17891 ** than 1GiB) the value returned might be less than the true string length.
17892 */
17893 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
17894 const char *z2 = z;
17895 while( *z2 ){ z2++; }
17896 return 0x3fffffff & (int)(z2 - z);
17897 }
17898
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17899 /*
17900 ** Set the most recent error code and error string for the sqlite
17901 ** handle "db". The error code is set to "err_code".
17902 **
17903 ** If it is not NULL, string zFormat specifies the format of the
@@ -17881,10 +17952,11 @@
17952 */
17953 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
17954 va_list ap;
17955 sqlite3 *db = pParse->db;
17956 pParse->nErr++;
17957 testcase( pParse->zErrMsg!=0 );
17958 sqlite3DbFree(db, pParse->zErrMsg);
17959 va_start(ap, zFormat);
17960 pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap);
17961 va_end(ap);
17962 if( pParse->rc==SQLITE_OK ){
@@ -17904,40 +17976,48 @@
17976 /*
17977 ** Convert an SQL-style quoted string into a normal string by removing
17978 ** the quote characters. The conversion is done in-place. If the
17979 ** input does not begin with a quote character, then this routine
17980 ** is a no-op.
17981 **
17982 ** The input string must be zero-terminated. A new zero-terminator
17983 ** is added to the dequoted string.
17984 **
17985 ** The return value is -1 if no dequoting occurs or the length of the
17986 ** dequoted string, exclusive of the zero terminator, if dequoting does
17987 ** occur.
17988 **
17989 ** 2002-Feb-14: This routine is extended to remove MS-Access style
17990 ** brackets from around identifers. For example: "[a-b-c]" becomes
17991 ** "a-b-c".
17992 */
17993 SQLITE_PRIVATE int sqlite3Dequote(char *z){
17994 char quote;
17995 int i, j;
17996 if( z==0 ) return -1;
17997 quote = z[0];
17998 switch( quote ){
17999 case '\'': break;
18000 case '"': break;
18001 case '`': break; /* For MySQL compatibility */
18002 case '[': quote = ']'; break; /* For MS SqlServer compatibility */
18003 default: return -1;
18004 }
18005 for(i=1, j=0; ALWAYS(z[i]); i++){
18006 if( z[i]==quote ){
18007 if( z[i+1]==quote ){
18008 z[j++] = quote;
18009 i++;
18010 }else{
 
18011 break;
18012 }
18013 }else{
18014 z[j++] = z[i];
18015 }
18016 }
18017 z[j] = 0;
18018 return j;
18019 }
18020
18021 /* Convenient short-hand */
18022 #define UpperToLower sqlite3UpperToLower
18023
@@ -17959,14 +18039,19 @@
18039 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18040 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
18041 }
18042
18043 /*
18044 ** Return TRUE if z is a pure numeric string. Return FALSE and leave
18045 ** *realnum unchanged if the string contains any character which is not
18046 ** part of a number.
18047 **
18048 ** If the string is pure numeric, set *realnum to TRUE if the string
18049 ** contains the '.' character or an "E+000" style exponentiation suffix.
18050 ** Otherwise set *realnum to FALSE. Note that just becaue *realnum is
18051 ** false does not mean that the number can be successfully converted into
18052 ** an integer - it might be too big.
18053 **
18054 ** An empty string is considered non-numeric.
18055 */
18056 SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
18057 int incr = (enc==SQLITE_UTF8?1:2);
@@ -17974,24 +18059,24 @@
18059 if( *z=='-' || *z=='+' ) z += incr;
18060 if( !sqlite3Isdigit(*z) ){
18061 return 0;
18062 }
18063 z += incr;
18064 *realnum = 0;
18065 while( sqlite3Isdigit(*z) ){ z += incr; }
18066 if( *z=='.' ){
18067 z += incr;
18068 if( !sqlite3Isdigit(*z) ) return 0;
18069 while( sqlite3Isdigit(*z) ){ z += incr; }
18070 *realnum = 1;
18071 }
18072 if( *z=='e' || *z=='E' ){
18073 z += incr;
18074 if( *z=='+' || *z=='-' ) z += incr;
18075 if( !sqlite3Isdigit(*z) ) return 0;
18076 while( sqlite3Isdigit(*z) ){ z += incr; }
18077 *realnum = 1;
18078 }
18079 return *z==0;
18080 }
18081
18082 /*
@@ -18146,29 +18231,29 @@
18231 return compare2pow63(zNum)<neg;
18232 }
18233 }
18234
18235 /*
18236 ** The string zNum represents an unsigned integer. There might be some other
18237 ** information following the integer too, but that part is ignored.
18238 ** If the integer that the prefix of zNum represents will fit in a
18239 ** 64-bit signed integer, return TRUE. Otherwise return FALSE.
18240 **
18241 ** If the negFlag parameter is true, that means that zNum really represents
18242 ** a negative number. (The leading "-" is omitted from zNum.) This
18243 ** parameter is needed to determine a boundary case. A string
18244 ** of "9223373036854775808" returns false if negFlag is false or true
18245 ** if negFlag is true.
18246 **
18247 ** Leading zeros are ignored.
18248 */
18249 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
18250 int i, c;
18251 int neg = 0;
18252
18253 assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */
18254
 
 
 
18255 if( negFlag ) neg = 1-neg;
18256 while( *zNum=='0' ){
18257 zNum++; /* Skip leading zeros. Ticket #2454 */
18258 }
18259 for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
@@ -18469,50 +18554,84 @@
18554 ** this function assumes the single-byte case has already been handled.
18555 */
18556 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
18557 u32 a,b;
18558
18559 /* The 1-byte case. Overwhelmingly the most common. Handled inline
18560 ** by the getVarin32() macro */
18561 a = *p;
18562 /* a: p0 (unmasked) */
18563 #ifndef getVarint32
18564 if (!(a&0x80))
18565 {
18566 /* Values between 0 and 127 */
18567 *v = a;
18568 return 1;
18569 }
18570 #endif
18571
18572 /* The 2-byte case */
18573 p++;
18574 b = *p;
18575 /* b: p1 (unmasked) */
18576 if (!(b&0x80))
18577 {
18578 /* Values between 128 and 16383 */
18579 a &= 0x7f;
18580 a = a<<7;
18581 *v = a | b;
18582 return 2;
18583 }
18584
18585 /* The 3-byte case */
18586 p++;
18587 a = a<<14;
18588 a |= *p;
18589 /* a: p0<<14 | p2 (unmasked) */
18590 if (!(a&0x80))
18591 {
18592 /* Values between 16384 and 2097151 */
18593 a &= (0x7f<<14)|(0x7f);
18594 b &= 0x7f;
18595 b = b<<7;
18596 *v = a | b;
18597 return 3;
18598 }
18599
18600 /* A 32-bit varint is used to store size information in btrees.
18601 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
18602 ** A 3-byte varint is sufficient, for example, to record the size
18603 ** of a 1048569-byte BLOB or string.
18604 **
18605 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
18606 ** rare larger cases can be handled by the slower 64-bit varint
18607 ** routine.
18608 */
18609 #if 1
18610 {
18611 u64 v64;
18612 u8 n;
18613
18614 p -= 2;
18615 n = sqlite3GetVarint(p, &v64);
18616 assert( n>3 && n<=9 );
18617 *v = (u32)v64;
18618 return n;
18619 }
18620
18621 #else
18622 /* For following code (kept for historical record only) shows an
18623 ** unrolling for the 3- and 4-byte varint cases. This code is
18624 ** slightly faster, but it is also larger and much harder to test.
18625 */
18626 p++;
18627 b = b<<14;
18628 b |= *p;
18629 /* b: p1<<14 | p3 (unmasked) */
18630 if (!(b&0x80))
18631 {
18632 /* Values between 2097152 and 268435455 */
18633 b &= (0x7f<<14)|(0x7f);
18634 a &= (0x7f<<14)|(0x7f);
18635 a = a<<7;
18636 *v = a | b;
18637 return 4;
@@ -18522,10 +18641,11 @@
18641 a = a<<14;
18642 a |= *p;
18643 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
18644 if (!(a&0x80))
18645 {
18646 /* Walues between 268435456 and 34359738367 */
18647 a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
18648 b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
18649 b = b<<7;
18650 *v = a | b;
18651 return 5;
@@ -18543,10 +18663,11 @@
18663 n = sqlite3GetVarint(p, &v64);
18664 assert( n>5 && n<=9 );
18665 *v = (u32)v64;
18666 return n;
18667 }
18668 #endif
18669 }
18670
18671 /*
18672 ** Return the number of bytes that will be needed to store the given
18673 ** 64-bit integer.
@@ -18554,11 +18675,11 @@
18675 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
18676 int i = 0;
18677 do{
18678 i++;
18679 v >>= 7;
18680 }while( v!=0 && ALWAYS(i<9) );
18681 return i;
18682 }
18683
18684
18685 /*
@@ -18692,17 +18813,22 @@
18813 */
18814 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
18815 u32 magic;
18816 if( db==0 ) return 0;
18817 magic = db->magic;
18818 if( magic!=SQLITE_MAGIC_OPEN
18819 #ifdef SQLITE_DEBUG
18820 && magic!=SQLITE_MAGIC_BUSY
18821 #endif
18822 ){
18823 return 0;
18824 }else{
18825 return 1;
18826 }
18827 }
18828 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
18829 u32 magic;
 
18830 magic = db->magic;
18831 if( magic!=SQLITE_MAGIC_SICK &&
18832 magic!=SQLITE_MAGIC_OPEN &&
18833 magic!=SQLITE_MAGIC_BUSY ) return 0;
18834 return 1;
@@ -18722,23 +18848,20 @@
18848 **
18849 *************************************************************************
18850 ** This is the implementation of generic hash-tables
18851 ** used in SQLite.
18852 **
18853 ** $Id: hash.c,v 1.37 2009/05/02 13:29:38 drh Exp $
18854 */
18855
18856 /* Turn bulk memory into a hash table object by initializing the
18857 ** fields of the Hash structure.
18858 **
18859 ** "pNew" is a pointer to the hash table that is to be initialized.
 
 
18860 */
18861 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
18862 assert( pNew!=0 );
 
18863 pNew->first = 0;
18864 pNew->count = 0;
18865 pNew->htsize = 0;
18866 pNew->ht = 0;
18867 }
@@ -18756,47 +18879,46 @@
18879 sqlite3_free(pH->ht);
18880 pH->ht = 0;
18881 pH->htsize = 0;
18882 while( elem ){
18883 HashElem *next_elem = elem->next;
 
 
 
18884 sqlite3_free(elem);
18885 elem = next_elem;
18886 }
18887 pH->count = 0;
18888 }
18889
18890 /*
18891 ** The hashing function.
18892 */
18893 static unsigned int strHash(const char *z, int nKey){
 
18894 int h = 0;
18895 assert( nKey>=0 );
18896 while( nKey > 0 ){
18897 h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
18898 nKey--;
18899 }
18900 return h;
 
 
 
 
18901 }
18902
18903
18904 /* Link pNew element into the hash table pH. If pEntry!=0 then also
18905 ** insert pNew into the pEntry hash bucket.
18906 */
18907 static void insertElement(
18908 Hash *pH, /* The complete hash table */
18909 struct _ht *pEntry, /* The entry into which pNew is inserted */
18910 HashElem *pNew /* The element to be inserted */
18911 ){
18912 HashElem *pHead; /* First element already in pEntry */
18913 if( pEntry ){
18914 pHead = pEntry->count ? pEntry->chain : 0;
18915 pEntry->count++;
18916 pEntry->chain = pNew;
18917 }else{
18918 pHead = 0;
18919 }
18920 if( pHead ){
18921 pNew->next = pHead;
18922 pNew->prev = pHead->prev;
18923 if( pHead->prev ){ pHead->prev->next = pNew; }
18924 else { pH->first = pNew; }
@@ -18805,73 +18927,77 @@
18927 pNew->next = pH->first;
18928 if( pH->first ){ pH->first->prev = pNew; }
18929 pNew->prev = 0;
18930 pH->first = pNew;
18931 }
 
 
18932 }
18933
18934
18935 /* Resize the hash table so that it cantains "new_size" buckets.
18936 **
18937 ** The hash table might fail to resize if sqlite3_malloc() fails or
18938 ** if the new size is the same as the prior size.
18939 ** Return TRUE if the resize occurs and false if not.
18940 */
18941 static int rehash(Hash *pH, unsigned int new_size){
18942 struct _ht *new_ht; /* The new hash table */
18943 HashElem *elem, *next_elem; /* For looping over existing elements */
18944
18945 #if SQLITE_MALLOC_SOFT_LIMIT>0
18946 if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
18947 new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
18948 }
18949 if( new_size==pH->htsize ) return 0;
18950 #endif
18951
18952 /* The inability to allocates space for a larger hash table is
18953 ** a performance hit but it is not a fatal error. So mark the
18954 ** allocation as a benign.
 
18955 */
18956 sqlite3BeginBenignMalloc();
18957 new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
18958 sqlite3EndBenignMalloc();
18959
18960 if( new_ht==0 ) return 0;
18961 sqlite3_free(pH->ht);
18962 pH->ht = new_ht;
18963 pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
18964 memset(new_ht, 0, new_size*sizeof(struct _ht));
18965 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
18966 unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
18967 next_elem = elem->next;
18968 insertElement(pH, &new_ht[h], elem);
18969 }
18970 return 1;
18971 }
18972
18973 /* This function (for internal use only) locates an element in an
18974 ** hash table that matches the given key. The hash for this key has
18975 ** already been computed and is passed as the 4th parameter.
18976 */
18977 static HashElem *findElementGivenHash(
18978 const Hash *pH, /* The pH to be searched */
18979 const char *pKey, /* The key we are searching for */
18980 int nKey, /* Bytes in key (not counting zero terminator) */
18981 unsigned int h /* The hash for this key. */
18982 ){
18983 HashElem *elem; /* Used to loop thru the element list */
18984 int count; /* Number of elements left to test */
18985
18986 if( pH->ht ){
18987 struct _ht *pEntry = &pH->ht[h];
18988 elem = pEntry->chain;
18989 count = pEntry->count;
18990 }else{
18991 elem = pH->first;
18992 count = pH->count;
18993 }
18994 while( count-- && ALWAYS(elem) ){
18995 if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
18996 return elem;
18997 }
18998 elem = elem->next;
18999 }
19000 return 0;
19001 }
19002
19003 /* Remove a single entry from the hash table given a pointer to that
@@ -18878,11 +19004,11 @@
19004 ** element and a hash on the element's key.
19005 */
19006 static void removeElementGivenHash(
19007 Hash *pH, /* The pH containing "elem" */
19008 HashElem* elem, /* The element to be removed from the pH */
19009 unsigned int h /* Hash value for the element */
19010 ){
19011 struct _ht *pEntry;
19012 if( elem->prev ){
19013 elem->prev->next = elem->next;
19014 }else{
@@ -18889,20 +19015,17 @@
19015 pH->first = elem->next;
19016 }
19017 if( elem->next ){
19018 elem->next->prev = elem->prev;
19019 }
19020 if( pH->ht ){
19021 pEntry = &pH->ht[h];
19022 if( pEntry->chain==elem ){
19023 pEntry->chain = elem->next;
19024 }
19025 pEntry->count--;
19026 assert( pEntry->count>=0 );
 
 
 
19027 }
19028 sqlite3_free( elem );
19029 pH->count--;
19030 if( pH->count<=0 ){
19031 assert( pH->first==0 );
@@ -18909,108 +19032,86 @@
19032 assert( pH->count==0 );
19033 sqlite3HashClear(pH);
19034 }
19035 }
19036
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19037 /* Attempt to locate an element of the hash table pH with a key
19038 ** that matches pKey,nKey. Return the data for this element if it is
19039 ** found, or NULL if there is no match.
19040 */
19041 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
19042 HashElem *elem; /* The element that matches key */
19043 unsigned int h; /* A hash on key */
19044
19045 assert( pH!=0 );
19046 assert( pKey!=0 );
19047 assert( nKey>=0 );
19048 if( pH->ht ){
19049 h = strHash(pKey, nKey) % pH->htsize;
19050 }else{
19051 h = 0;
19052 }
19053 elem = findElementGivenHash(pH, pKey, nKey, h);
19054 return elem ? elem->data : 0;
19055 }
19056
19057 /* Insert an element into the hash table pH. The key is pKey,nKey
19058 ** and the data is "data".
19059 **
19060 ** If no element exists with a matching key, then a new
19061 ** element is created and NULL is returned.
 
19062 **
19063 ** If another element already exists with the same key, then the
19064 ** new data replaces the old data and the old data is returned.
19065 ** The key is not copied in this instance. If a malloc fails, then
19066 ** the new data is returned and the hash table is unchanged.
19067 **
19068 ** If the "data" parameter to this function is NULL, then the
19069 ** element corresponding to "key" is removed from the hash table.
19070 */
19071 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
19072 unsigned int h; /* the hash of the key modulo hash table size */
 
19073 HashElem *elem; /* Used to loop thru the element list */
19074 HashElem *new_elem; /* New element added to the pH */
19075
19076 assert( pH!=0 );
19077 assert( pKey!=0 );
19078 assert( nKey>=0 );
19079 if( pH->htsize ){
19080 h = strHash(pKey, nKey) % pH->htsize;
19081 }else{
19082 h = 0;
19083 }
19084 elem = findElementGivenHash(pH,pKey,nKey,h);
19085 if( elem ){
19086 void *old_data = elem->data;
19087 if( data==0 ){
19088 removeElementGivenHash(pH,elem,h);
19089 }else{
19090 elem->data = data;
19091 elem->pKey = pKey;
19092 assert(nKey==elem->nKey);
19093 }
19094 return old_data;
19095 }
19096 if( data==0 ) return 0;
19097 new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
19098 if( new_elem==0 ) return data;
19099 new_elem->pKey = pKey;
 
 
 
 
 
 
 
 
 
19100 new_elem->nKey = nKey;
19101 new_elem->data = data;
19102 pH->count++;
19103 if( pH->count>=10 && pH->count > 2*pH->htsize ){
19104 if( rehash(pH, pH->count*2) && pH->htsize ){
19105 h = strHash(pKey, nKey) % pH->htsize;
19106 }
19107 }
19108 if( pH->ht ){
19109 insertElement(pH, &pH->ht[h], new_elem);
19110 }else{
19111 insertElement(pH, 0, new_elem);
19112 }
 
 
 
 
 
 
 
 
19113 return 0;
19114 }
19115
19116 /************** End of hash.c ************************************************/
19117 /************** Begin file opcodes.c *****************************************/
@@ -19028,78 +19129,78 @@
19129 /* 7 */ "Savepoint",
19130 /* 8 */ "RowKey",
19131 /* 9 */ "SCopy",
19132 /* 10 */ "OpenWrite",
19133 /* 11 */ "If",
19134 /* 12 */ "CollSeq",
19135 /* 13 */ "OpenRead",
19136 /* 14 */ "Expire",
19137 /* 15 */ "AutoCommit",
19138 /* 16 */ "Pagecount",
19139 /* 17 */ "IntegrityCk",
19140 /* 18 */ "Sort",
19141 /* 19 */ "Not",
19142 /* 20 */ "Copy",
19143 /* 21 */ "Trace",
19144 /* 22 */ "Function",
19145 /* 23 */ "IfNeg",
19146 /* 24 */ "Noop",
19147 /* 25 */ "Return",
19148 /* 26 */ "NewRowid",
19149 /* 27 */ "Variable",
19150 /* 28 */ "String",
19151 /* 29 */ "RealAffinity",
19152 /* 30 */ "VRename",
19153 /* 31 */ "ParseSchema",
19154 /* 32 */ "VOpen",
19155 /* 33 */ "Close",
19156 /* 34 */ "CreateIndex",
19157 /* 35 */ "IsUnique",
19158 /* 36 */ "NotFound",
19159 /* 37 */ "Int64",
19160 /* 38 */ "MustBeInt",
19161 /* 39 */ "Halt",
19162 /* 40 */ "Rowid",
19163 /* 41 */ "IdxLT",
19164 /* 42 */ "AddImm",
19165 /* 43 */ "Statement",
19166 /* 44 */ "RowData",
19167 /* 45 */ "MemMax",
19168 /* 46 */ "NotExists",
19169 /* 47 */ "Gosub",
19170 /* 48 */ "Integer",
19171 /* 49 */ "Prev",
19172 /* 50 */ "RowSetRead",
19173 /* 51 */ "RowSetAdd",
19174 /* 52 */ "VColumn",
19175 /* 53 */ "CreateTable",
19176 /* 54 */ "Last",
19177 /* 55 */ "SeekLe",
19178 /* 56 */ "IncrVacuum",
19179 /* 57 */ "IdxRowid",
19180 /* 58 */ "ResetCount",
19181 /* 59 */ "ContextPush",
19182 /* 60 */ "Yield",
19183 /* 61 */ "DropTrigger",
19184 /* 62 */ "DropIndex",
19185 /* 63 */ "IdxGE",
19186 /* 64 */ "IdxDelete",
19187 /* 65 */ "Vacuum",
19188 /* 66 */ "Or",
19189 /* 67 */ "And",
19190 /* 68 */ "IfNot",
19191 /* 69 */ "DropTable",
19192 /* 70 */ "SeekLt",
19193 /* 71 */ "IsNull",
19194 /* 72 */ "NotNull",
19195 /* 73 */ "Ne",
19196 /* 74 */ "Eq",
19197 /* 75 */ "Gt",
19198 /* 76 */ "Le",
19199 /* 77 */ "Lt",
19200 /* 78 */ "Ge",
19201 /* 79 */ "MakeRecord",
19202 /* 80 */ "BitAnd",
19203 /* 81 */ "BitOr",
19204 /* 82 */ "ShiftLeft",
19205 /* 83 */ "ShiftRight",
19206 /* 84 */ "Add",
@@ -19106,34 +19207,34 @@
19207 /* 85 */ "Subtract",
19208 /* 86 */ "Multiply",
19209 /* 87 */ "Divide",
19210 /* 88 */ "Remainder",
19211 /* 89 */ "Concat",
19212 /* 90 */ "ResultRow",
19213 /* 91 */ "Delete",
19214 /* 92 */ "AggFinal",
19215 /* 93 */ "BitNot",
19216 /* 94 */ "String8",
19217 /* 95 */ "Compare",
19218 /* 96 */ "Goto",
19219 /* 97 */ "TableLock",
19220 /* 98 */ "Clear",
19221 /* 99 */ "VerifyCookie",
19222 /* 100 */ "AggStep",
19223 /* 101 */ "SetNumColumns",
19224 /* 102 */ "Transaction",
19225 /* 103 */ "VFilter",
19226 /* 104 */ "VDestroy",
19227 /* 105 */ "ContextPop",
19228 /* 106 */ "Next",
19229 /* 107 */ "Count",
19230 /* 108 */ "IdxInsert",
19231 /* 109 */ "SeekGe",
19232 /* 110 */ "Insert",
19233 /* 111 */ "Destroy",
19234 /* 112 */ "ReadCookie",
19235 /* 113 */ "RowSetTest",
19236 /* 114 */ "LoadAnalysis",
19237 /* 115 */ "Explain",
19238 /* 116 */ "HaltIfNull",
19239 /* 117 */ "OpenPseudo",
19240 /* 118 */ "OpenEphemeral",
@@ -25901,11 +26002,11 @@
26002 **
26003 ******************************************************************************
26004 **
26005 ** This file contains code that is specific to windows.
26006 **
26007 ** $Id: os_win.c,v 1.156 2009/04/23 19:08:33 shane Exp $
26008 */
26009 #if SQLITE_OS_WIN /* This file is used for windows only */
26010
26011
26012 /*
@@ -27422,20 +27523,27 @@
27523 if( flags & SQLITE_OPEN_READWRITE ){
27524 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
27525 }else{
27526 dwDesiredAccess = GENERIC_READ;
27527 }
27528 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
27529 ** created. SQLite doesn't use it to indicate "exclusive access"
27530 ** as it is usually understood.
27531 */
27532 assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
27533 if( flags & SQLITE_OPEN_EXCLUSIVE ){
27534 /* Creates a new file, only if it does not already exist. */
27535 /* If the file exists, it fails. */
27536 dwCreationDisposition = CREATE_NEW;
27537 }else if( flags & SQLITE_OPEN_CREATE ){
27538 /* Open existing file, or create if it doesn't exist */
27539 dwCreationDisposition = OPEN_ALWAYS;
27540 }else{
27541 /* Opens a file, only if it exists. */
27542 dwCreationDisposition = OPEN_EXISTING;
27543 }
27544 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
 
 
 
 
27545 if( flags & SQLITE_OPEN_DELETEONCLOSE ){
27546 #if SQLITE_OS_WINCE
27547 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
27548 isTemp = 1;
27549 #else
@@ -27710,17 +27818,15 @@
27818 if( rc == SQLITE_OK )
27819 {
27820 void *zConverted = convertUtf8Filename(zFullpath);
27821 if( zConverted ){
27822 if( isNT() ){
 
27823 /* trim path to just drive reference */
27824 WCHAR *p = zConverted;
27825 for(;*p;p++){
27826 if( *p == '\\' ){
27827 *p = '\0';
 
27828 break;
27829 }
27830 }
27831 dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
27832 &dwDummy,
@@ -27727,17 +27833,15 @@
27833 &bytesPerSector,
27834 &dwDummy,
27835 &dwDummy);
27836 #if SQLITE_OS_WINCE==0
27837 }else{
 
27838 /* trim path to just drive reference */
27839 CHAR *p = (CHAR *)zConverted;
27840 for(;*p;p++){
27841 if( *p == '\\' ){
27842 *p = '\0';
 
27843 break;
27844 }
27845 }
27846 dwRet = GetDiskFreeSpaceA((CHAR*)zConverted,
27847 &dwDummy,
@@ -28987,11 +29091,11 @@
29091 ** sqlite3_pcache interface). It also contains part of the implementation
29092 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
29093 ** If the default page cache implementation is overriden, then neither of
29094 ** these two features are available.
29095 **
29096 ** @(#) $Id: pcache1.c,v 1.11 2009/04/14 18:44:39 aswift Exp $
29097 */
29098
29099
29100 typedef struct PCache1 PCache1;
29101 typedef struct PgHdr1 PgHdr1;
@@ -29497,11 +29601,11 @@
29601 goto fetch_out;
29602 }
29603
29604 /* Step 4. Try to recycle a page buffer if appropriate. */
29605 if( pCache->bPurgeable && pcache1.pLruTail && (
29606 (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
29607 )){
29608 pPage = pcache1.pLruTail;
29609 pcache1RemoveFromHash(pPage);
29610 pcache1PinPage(pPage);
29611 if( pPage->pCache->szPage!=pCache->szPage ){
@@ -29735,50 +29839,92 @@
29839 ** May you find forgiveness for yourself and forgive others.
29840 ** May you share freely, never taking more than you give.
29841 **
29842 *************************************************************************
29843 **
29844 ** This module implements an object we call a "RowSet".
29845 **
29846 ** The RowSet object is a collection of rowids. Rowids
29847 ** are inserted into the RowSet in an arbitrary order. Inserts
29848 ** can be intermixed with tests to see if a given rowid has been
29849 ** previously inserted into the RowSet.
29850 **
29851 ** After all inserts are finished, it is possible to extract the
29852 ** elements of the RowSet in sorted order. Once this extraction
29853 ** process has started, no new elements may be inserted.
29854 **
29855 ** Hence, the primitive operations for a RowSet are:
29856 **
29857 ** CREATE
29858 ** INSERT
29859 ** TEST
29860 ** SMALLEST
29861 ** DESTROY
29862 **
29863 ** The CREATE and DESTROY primitives are the constructor and destructor,
29864 ** obviously. The INSERT primitive adds a new element to the RowSet.
29865 ** TEST checks to see if an element is already in the RowSet. SMALLEST
29866 ** extracts the least value from the RowSet.
29867 **
29868 ** The INSERT primitive might allocate additional memory. Memory is
29869 ** allocated in chunks so most INSERTs do no allocation. There is an
29870 ** upper bound on the size of allocated memory. No memory is freed
29871 ** until DESTROY.
29872 **
29873 ** The TEST primitive includes a "batch" number. The TEST primitive
29874 ** will only see elements that were inserted before the last change
29875 ** in the batch number. In other words, if an INSERT occurs between
29876 ** two TESTs where the TESTs have the same batch nubmer, then the
29877 ** value added by the INSERT will not be visible to the second TEST.
29878 ** The initial batch number is zero, so if the very first TEST contains
29879 ** a non-zero batch number, it will see all prior INSERTs.
29880 **
29881 ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
29882 ** that is attempted.
29883 **
29884 ** The cost of an INSERT is roughly constant. (Sometime new memory
29885 ** has to be allocated on an INSERT.) The cost of a TEST with a new
29886 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
29887 ** The cost of a TEST using the same batch number is O(logN). The cost
29888 ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
29889 ** primitives are constant time. The cost of DESTROY is O(N).
29890 **
29891 ** There is an added cost of O(N) when switching between TEST and
29892 ** SMALLEST primitives.
29893 **
29894 ** $Id: rowset.c,v 1.6 2009/04/22 15:32:59 drh Exp $
29895 */
29896
29897
29898 /*
29899 ** Target size for allocation chunks.
29900 */
29901 #define ROWSET_ALLOCATION_SIZE 1024
29902
29903 /*
29904 ** The number of rowset entries per allocation chunk.
29905 */
29906 #define ROWSET_ENTRY_PER_CHUNK \
29907 ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
29908
29909 /*
29910 ** Each entry in a RowSet is an instance of the following object.
 
29911 */
29912 struct RowSetEntry {
29913 i64 v; /* ROWID value for this entry */
29914 struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
29915 struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
29916 };
29917
29918 /*
29919 ** RowSetEntry objects are allocated in large chunks (instances of the
29920 ** following structure) to reduce memory allocation overhead. The
29921 ** chunks are kept on a linked list so that they can be deallocated
29922 ** when the RowSet is destroyed.
29923 */
29924 struct RowSetChunk {
29925 struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
29926 struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
29927 };
29928
29929 /*
29930 ** A RowSet in an instance of the following structure.
@@ -29786,15 +29932,17 @@
29932 ** A typedef of this structure if found in sqliteInt.h.
29933 */
29934 struct RowSet {
29935 struct RowSetChunk *pChunk; /* List of all chunk allocations */
29936 sqlite3 *db; /* The database connection */
29937 struct RowSetEntry *pEntry; /* List of entries using pRight */
29938 struct RowSetEntry *pLast; /* Last entry on the pEntry list */
29939 struct RowSetEntry *pFresh; /* Source of new entry objects */
29940 struct RowSetEntry *pTree; /* Binary tree of entries */
29941 u16 nFresh; /* Number of objects on pFresh */
29942 u8 isSorted; /* True if pEntry is sorted */
29943 u8 iBatch; /* Current insert batch */
29944 };
29945
29946 /*
29947 ** Turn bulk memory into a RowSet object. N bytes of memory
29948 ** are available at pSpace. The db pointer is used as a memory context
@@ -29813,29 +29961,34 @@
29961 p = pSpace;
29962 p->pChunk = 0;
29963 p->db = db;
29964 p->pEntry = 0;
29965 p->pLast = 0;
29966 p->pTree = 0;
29967 p->pFresh = (struct RowSetEntry*)&p[1];
29968 p->nFresh = (u16)((N - sizeof(*p))/sizeof(struct RowSetEntry));
29969 p->isSorted = 1;
29970 p->iBatch = 0;
29971 return p;
29972 }
29973
29974 /*
29975 ** Deallocate all chunks from a RowSet. This frees all memory that
29976 ** the RowSet has allocated over its lifetime. This routine is
29977 ** the destructor for the RowSet.
29978 */
29979 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
29980 struct RowSetChunk *pChunk, *pNextChunk;
29981 for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
29982 pNextChunk = pChunk->pNextChunk;
29983 sqlite3DbFree(p->db, pChunk);
29984 }
29985 p->pChunk = 0;
29986 p->nFresh = 0;
29987 p->pEntry = 0;
29988 p->pLast = 0;
29989 p->pTree = 0;
29990 p->isSorted = 1;
29991 }
29992
29993 /*
29994 ** Insert a new value into a RowSet.
@@ -29842,128 +29995,265 @@
29995 **
29996 ** The mallocFailed flag of the database connection is set if a
29997 ** memory allocation fails.
29998 */
29999 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
30000 struct RowSetEntry *pEntry; /* The new entry */
30001 struct RowSetEntry *pLast; /* The last prior entry */
30002 assert( p!=0 );
30003 if( p->nFresh==0 ){
30004 struct RowSetChunk *pNew;
30005 pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
30006 if( pNew==0 ){
30007 return;
30008 }
30009 pNew->pNextChunk = p->pChunk;
30010 p->pChunk = pNew;
30011 p->pFresh = pNew->aEntry;
30012 p->nFresh = ROWSET_ENTRY_PER_CHUNK;
30013 }
30014 pEntry = p->pFresh++;
30015 p->nFresh--;
30016 pEntry->v = rowid;
30017 pEntry->pRight = 0;
30018 pLast = p->pLast;
30019 if( pLast ){
30020 if( p->isSorted && rowid<=pLast->v ){
30021 p->isSorted = 0;
30022 }
30023 pLast->pRight = pEntry;
30024 }else{
30025 assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
30026 p->pEntry = pEntry;
30027 }
30028 p->pLast = pEntry;
30029 }
30030
30031 /*
30032 ** Merge two lists of RowSetEntry objects. Remove duplicates.
30033 **
30034 ** The input lists are connected via pRight pointers and are
30035 ** assumed to each already be in sorted order.
30036 */
30037 static struct RowSetEntry *rowSetMerge(
30038 struct RowSetEntry *pA, /* First sorted list to be merged */
30039 struct RowSetEntry *pB /* Second sorted list to be merged */
30040 ){
30041 struct RowSetEntry head;
30042 struct RowSetEntry *pTail;
30043
30044 pTail = &head;
30045 while( pA && pB ){
30046 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
30047 assert( pB->pRight==0 || pB->v<=pB->pRight->v );
30048 if( pA->v<pB->v ){
30049 pTail->pRight = pA;
30050 pA = pA->pRight;
30051 pTail = pTail->pRight;
30052 }else if( pB->v<pA->v ){
30053 pTail->pRight = pB;
30054 pB = pB->pRight;
30055 pTail = pTail->pRight;
30056 }else{
30057 pA = pA->pRight;
30058 }
30059 }
30060 if( pA ){
30061 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
30062 pTail->pRight = pA;
30063 }else{
30064 assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
30065 pTail->pRight = pB;
30066 }
30067 return head.pRight;
30068 }
30069
30070 /*
30071 ** Sort all elements on the pEntry list of the RowSet into ascending order.
30072 */
30073 static void rowSetSort(RowSet *p){
30074 unsigned int i;
30075 struct RowSetEntry *pEntry;
30076 struct RowSetEntry *aBucket[40];
30077
30078 assert( p->isSorted==0 );
30079 memset(aBucket, 0, sizeof(aBucket));
30080 while( p->pEntry ){
30081 pEntry = p->pEntry;
30082 p->pEntry = pEntry->pRight;
30083 pEntry->pRight = 0;
30084 for(i=0; aBucket[i]; i++){
30085 pEntry = rowSetMerge(aBucket[i], pEntry);
30086 aBucket[i] = 0;
30087 }
30088 aBucket[i] = pEntry;
30089 }
30090 pEntry = 0;
30091 for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
30092 pEntry = rowSetMerge(pEntry, aBucket[i]);
30093 }
30094 p->pEntry = pEntry;
30095 p->pLast = 0;
30096 p->isSorted = 1;
30097 }
30098
30099
30100 /*
30101 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
30102 ** Convert this tree into a linked list connected by the pRight pointers
30103 ** and return pointers to the first and last elements of the new list.
30104 */
30105 static void rowSetTreeToList(
30106 struct RowSetEntry *pIn, /* Root of the input tree */
30107 struct RowSetEntry **ppFirst, /* Write head of the output list here */
30108 struct RowSetEntry **ppLast /* Write tail of the output list here */
30109 ){
30110 assert( pIn!=0 );
30111 if( pIn->pLeft ){
30112 struct RowSetEntry *p;
30113 rowSetTreeToList(pIn->pLeft, ppFirst, &p);
30114 p->pRight = pIn;
30115 }else{
30116 *ppFirst = pIn;
30117 }
30118 if( pIn->pRight ){
30119 rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
30120 }else{
30121 *ppLast = pIn;
30122 }
30123 assert( (*ppLast)->pRight==0 );
30124 }
30125
30126
30127 /*
30128 ** Convert a sorted list of elements (connected by pRight) into a binary
30129 ** tree with depth of iDepth. A depth of 1 means the tree contains a single
30130 ** node taken from the head of *ppList. A depth of 2 means a tree with
30131 ** three nodes. And so forth.
30132 **
30133 ** Use as many entries from the input list as required and update the
30134 ** *ppList to point to the unused elements of the list. If the input
30135 ** list contains too few elements, then construct an incomplete tree
30136 ** and leave *ppList set to NULL.
30137 **
30138 ** Return a pointer to the root of the constructed binary tree.
30139 */
30140 static struct RowSetEntry *rowSetNDeepTree(
30141 struct RowSetEntry **ppList,
30142 int iDepth
30143 ){
30144 struct RowSetEntry *p; /* Root of the new tree */
30145 struct RowSetEntry *pLeft; /* Left subtree */
30146 if( *ppList==0 ){
30147 return 0;
30148 }
30149 if( iDepth==1 ){
30150 p = *ppList;
30151 *ppList = p->pRight;
30152 p->pLeft = p->pRight = 0;
30153 return p;
30154 }
30155 pLeft = rowSetNDeepTree(ppList, iDepth-1);
30156 p = *ppList;
30157 if( p==0 ){
30158 return pLeft;
30159 }
30160 p->pLeft = pLeft;
30161 *ppList = p->pRight;
30162 p->pRight = rowSetNDeepTree(ppList, iDepth-1);
30163 return p;
30164 }
30165
30166 /*
30167 ** Convert a sorted list of elements into a binary tree. Make the tree
30168 ** as deep as it needs to be in order to contain the entire list.
30169 */
30170 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
30171 int iDepth; /* Depth of the tree so far */
30172 struct RowSetEntry *p; /* Current tree root */
30173 struct RowSetEntry *pLeft; /* Left subtree */
30174
30175 assert( pList!=0 );
30176 p = pList;
30177 pList = p->pRight;
30178 p->pLeft = p->pRight = 0;
30179 for(iDepth=1; pList; iDepth++){
30180 pLeft = p;
30181 p = pList;
30182 pList = p->pRight;
30183 p->pLeft = pLeft;
30184 p->pRight = rowSetNDeepTree(&pList, iDepth);
30185 }
30186 return p;
30187 }
30188
30189 /*
30190 ** Convert the list in p->pEntry into a sorted list if it is not
30191 ** sorted already. If there is a binary tree on p->pTree, then
30192 ** convert it into a list too and merge it into the p->pEntry list.
30193 */
30194 static void rowSetToList(RowSet *p){
30195 if( !p->isSorted ){
30196 rowSetSort(p);
30197 }
30198 if( p->pTree ){
30199 struct RowSetEntry *pHead, *pTail;
30200 rowSetTreeToList(p->pTree, &pHead, &pTail);
30201 p->pTree = 0;
30202 p->pEntry = rowSetMerge(p->pEntry, pHead);
30203 }
30204 }
30205
30206 /*
30207 ** Extract the smallest element from the RowSet.
30208 ** Write the element into *pRowid. Return 1 on success. Return
30209 ** 0 if the RowSet is already empty.
30210 **
30211 ** After this routine has been called, the sqlite3RowSetInsert()
30212 ** routine may not be called again.
30213 */
30214 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
30215 rowSetToList(p);
 
 
30216 if( p->pEntry ){
30217 *pRowid = p->pEntry->v;
30218 p->pEntry = p->pEntry->pRight;
30219 if( p->pEntry==0 ){
30220 sqlite3RowSetClear(p);
30221 }
30222 return 1;
30223 }else{
30224 return 0;
30225 }
30226 }
30227
30228 /*
30229 ** Check to see if element iRowid was inserted into the the rowset as
30230 ** part of any insert batch prior to iBatch. Return 1 or 0.
30231 */
30232 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
30233 struct RowSetEntry *p;
30234 if( iBatch!=pRowSet->iBatch ){
30235 if( pRowSet->pEntry ){
30236 rowSetToList(pRowSet);
30237 pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
30238 pRowSet->pEntry = 0;
30239 pRowSet->pLast = 0;
30240 }
30241 pRowSet->iBatch = iBatch;
30242 }
30243 p = pRowSet->pTree;
30244 while( p ){
30245 if( p->v<iRowid ){
30246 p = p->pRight;
30247 }else if( p->v>iRowid ){
30248 p = p->pLeft;
30249 }else{
30250 return 1;
30251 }
30252 }
30253 return 0;
30254 }
30255
30256 /************** End of rowset.c **********************************************/
30257 /************** Begin file pager.c *******************************************/
30258 /*
30259 ** 2001 September 15
@@ -29983,11 +30273,11 @@
30273 ** is separate from the database file. The pager also implements file
30274 ** locking to prevent two processes from writing the same database
30275 ** file simultaneously, or one process from reading the database while
30276 ** another is writing.
30277 **
30278 ** @(#) $Id: pager.c,v 1.586 2009/05/06 18:57:10 shane Exp $
30279 */
30280 #ifndef SQLITE_OMIT_DISKIO
30281
30282 /*
30283 ** Macros for troubleshooting. Normally turned off
@@ -30193,10 +30483,16 @@
30483 ** needSync
30484 **
30485 ** TODO: It might be easier to set this variable in writeJournalHdr()
30486 ** and writeMasterJournal() only. Change its meaning to "unsynced data
30487 ** has been written to the journal".
30488 **
30489 ** subjInMemory
30490 **
30491 ** This is a boolean variable. If true, then any required sub-journal
30492 ** is opened as an in-memory journal file. If false, then in-memory
30493 ** sub-journals are only used for in-memory pager files.
30494 */
30495 struct Pager {
30496 sqlite3_vfs *pVfs; /* OS functions to use for IO */
30497 u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
30498 u8 journalMode; /* On of the PAGER_JOURNALMODE_* values */
@@ -30226,10 +30522,11 @@
30522 u8 journalStarted; /* True if header of journal is synced */
30523 u8 changeCountDone; /* Set after incrementing the change-counter */
30524 u8 setMaster; /* True if a m-j name has been written to jrnl */
30525 u8 doNotSync; /* Boolean. While true, do not spill the cache */
30526 u8 dbSizeValid; /* Set when dbSize is correct */
30527 u8 subjInMemory; /* True to use in-memory sub-journals */
30528 Pgno dbSize; /* Number of pages in the database */
30529 Pgno dbOrigSize; /* dbSize before the current transaction */
30530 Pgno dbFileSize; /* Number of pages in the database file */
30531 int errCode; /* One of several kinds of errors */
30532 int nRec; /* Pages journalled since last j-header written */
@@ -31005,10 +31302,11 @@
31302 */
31303 static void pager_reset(Pager *pPager){
31304 if( SQLITE_OK==pPager->errCode ){
31305 sqlite3BackupRestart(pPager->pBackup);
31306 sqlite3PcacheClear(pPager->pPCache);
31307 pPager->dbSizeValid = 0;
31308 }
31309 }
31310
31311 /*
31312 ** Free all structures in the Pager.aSavepoint[] array and set both
@@ -31018,11 +31316,11 @@
31316 static void releaseAllSavepoints(Pager *pPager){
31317 int ii; /* Iterator for looping through Pager.aSavepoint */
31318 for(ii=0; ii<pPager->nSavepoint; ii++){
31319 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
31320 }
31321 if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
31322 sqlite3OsClose(pPager->sjfd);
31323 }
31324 sqlite3_free(pPager->aSavepoint);
31325 pPager->aSavepoint = 0;
31326 pPager->nSavepoint = 0;
@@ -31254,11 +31552,15 @@
31552 sqlite3OsClose(pPager->jfd);
31553 if( !isMemoryJournal ){
31554 rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
31555 }
31556 }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
31557 if( pPager->journalOff==0 ){
31558 rc = SQLITE_OK;
31559 }else{
31560 rc = sqlite3OsTruncate(pPager->jfd, 0);
31561 }
31562 pPager->journalOff = 0;
31563 pPager->journalStarted = 0;
31564 }else if( pPager->exclusiveMode
31565 || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
31566 ){
@@ -33143,11 +33445,11 @@
33445 ROUND8(pVfs->szOsFile) + /* The main db file */
33446 journalFileSize * 2 + /* The two journal files */
33447 nPathname + 1 + /* zFilename */
33448 nPathname + 8 + 1 /* zJournal */
33449 );
33450 assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
33451 if( !pPtr ){
33452 sqlite3_free(zPathname);
33453 return SQLITE_NOMEM;
33454 }
33455 pPager = (Pager*)(pPtr);
@@ -33628,13 +33930,19 @@
33930 }
33931
33932 /*
33933 ** If the reference count has reached zero, rollback any active
33934 ** transaction and unlock the pager.
33935 **
33936 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
33937 ** the rollback journal, the unlock is not performed and there is
33938 ** nothing to rollback, so this routine is a no-op.
33939 */
33940 static void pagerUnlockIfUnused(Pager *pPager){
33941 if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
33942 && (!pPager->exclusiveMode || pPager->journalOff>0)
33943 ){
33944 pagerUnlockAndRollback(pPager);
33945 }
33946 }
33947
33948 /*
@@ -33858,11 +34166,11 @@
34166 ** sqlite3OsOpen() fails.
34167 */
34168 static int openSubJournal(Pager *pPager){
34169 int rc = SQLITE_OK;
34170 if( isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ){
34171 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
34172 sqlite3MemJournalOpen(pPager->sjfd);
34173 }else{
34174 rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
34175 }
34176 }
@@ -33977,14 +34285,23 @@
34285 ** of the journal file is deferred until there is an actual need to
34286 ** write to the journal. TODO: Why handle temporary files differently?
34287 **
34288 ** If the journal file is opened (or if it is already open), then a
34289 ** journal-header is written to the start of it.
34290 **
34291 ** If the subjInMemory argument is non-zero, then any sub-journal opened
34292 ** within this transaction will be opened as an in-memory file. This
34293 ** has no effect if the sub-journal is already opened (as it may be when
34294 ** running in exclusive mode) or if the transaction does not require a
34295 ** sub-journal. If the subjInMemory argument is zero, then any required
34296 ** sub-journal is implemented in-memory if pPager is an in-memory database,
34297 ** or using a temporary file otherwise.
34298 */
34299 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
34300 int rc = SQLITE_OK;
34301 assert( pPager->state!=PAGER_UNLOCK );
34302 pPager->subjInMemory = (u8)subjInMemory;
34303 if( pPager->state==PAGER_SHARED ){
34304 assert( pPager->pInJournal==0 );
34305 assert( !MEMDB && !pPager->tempFile );
34306
34307 /* Obtain a RESERVED lock on the database file. If the exFlag parameter
@@ -34065,11 +34382,11 @@
34382 **
34383 ** First check to see that the transaction journal exists and
34384 ** create it if it does not.
34385 */
34386 assert( pPager->state!=PAGER_UNLOCK );
34387 rc = sqlite3PagerBegin(pPager, 0, pPager->subjInMemory);
34388 if( rc!=SQLITE_OK ){
34389 return rc;
34390 }
34391 assert( pPager->state>=PAGER_RESERVED );
34392 if( !isOpen(pPager->jfd) && pPager->useJournal
@@ -35148,15 +35465,18 @@
35465 ** PAGER_JOURNALMODE_TRUNCATE
35466 ** PAGER_JOURNALMODE_PERSIST
35467 ** PAGER_JOURNALMODE_OFF
35468 ** PAGER_JOURNALMODE_MEMORY
35469 **
35470 ** If the parameter is not _QUERY, then the journal_mode is set to the
35471 ** value specified if the change is allowed. The change is disallowed
35472 ** for the following reasons:
35473 **
35474 ** * An in-memory database can only have its journal_mode set to _OFF
35475 ** or _MEMORY.
35476 **
35477 ** * The journal mode may not be changed while a transaction is active.
35478 **
35479 ** The returned indicate the current (possibly updated) journal-mode.
35480 */
35481 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
35482 assert( eMode==PAGER_JOURNALMODE_QUERY
@@ -35164,12 +35484,19 @@
35484 || eMode==PAGER_JOURNALMODE_TRUNCATE
35485 || eMode==PAGER_JOURNALMODE_PERSIST
35486 || eMode==PAGER_JOURNALMODE_OFF
35487 || eMode==PAGER_JOURNALMODE_MEMORY );
35488 assert( PAGER_JOURNALMODE_QUERY<0 );
35489 if( eMode>=0
35490 && (!MEMDB || eMode==PAGER_JOURNALMODE_MEMORY
35491 || eMode==PAGER_JOURNALMODE_OFF)
35492 && !pPager->dbModified
35493 && (!isOpen(pPager->jfd) || 0==pPager->journalOff)
35494 ){
35495 if( isOpen(pPager->jfd) ){
35496 sqlite3OsClose(pPager->jfd);
35497 }
35498 pPager->journalMode = (u8)eMode;
35499 }
35500 return (int)pPager->journalMode;
35501 }
35502
@@ -36210,11 +36537,11 @@
36537 ** May you do good and not evil.
36538 ** May you find forgiveness for yourself and forgive others.
36539 ** May you share freely, never taking more than you give.
36540 **
36541 *************************************************************************
36542 ** $Id: btree.c,v 1.608 2009/05/06 18:57:10 shane Exp $
36543 **
36544 ** This file implements a external (disk-based) database using BTrees.
36545 ** See the header comment on "btreeInt.h" for additional information.
36546 ** Including a description of file format and an overview of operation.
36547 */
@@ -36962,22 +37289,63 @@
37289 ** Compute the total number of bytes that a Cell needs in the cell
37290 ** data area of the btree-page. The return number includes the cell
37291 ** data header and the local payload, but not any overflow page or
37292 ** the space used by the cell pointer.
37293 */
37294 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
37295 u8 *pIter = &pCell[pPage->childPtrSize];
37296 u32 nSize;
37297
37298 #ifdef SQLITE_DEBUG
37299 /* The value returned by this function should always be the same as
37300 ** the (CellInfo.nSize) value found by doing a full parse of the
37301 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
37302 ** this function verifies that this invariant is not violated. */
37303 CellInfo debuginfo;
37304 sqlite3BtreeParseCellPtr(pPage, pCell, &debuginfo);
37305 #endif
37306
37307 if( pPage->intKey ){
37308 u8 *pEnd;
37309 if( pPage->hasData ){
37310 pIter += getVarint32(pIter, nSize);
37311 }else{
37312 nSize = 0;
37313 }
37314
37315 /* pIter now points at the 64-bit integer key value, a variable length
37316 ** integer. The following block moves pIter to point at the first byte
37317 ** past the end of the key value. */
37318 pEnd = &pIter[9];
37319 while( (*pIter++)&0x80 && pIter<pEnd );
37320 }else{
37321 pIter += getVarint32(pIter, nSize);
37322 }
37323
37324 if( nSize>pPage->maxLocal ){
37325 int minLocal = pPage->minLocal;
37326 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
37327 if( nSize>pPage->maxLocal ){
37328 nSize = minLocal;
37329 }
37330 nSize += 4;
37331 }
37332 nSize += (pIter - pCell);
37333
37334 /* The minimum size of any cell is 4 bytes. */
37335 if( nSize<4 ){
37336 nSize = 4;
37337 }
37338
37339 assert( nSize==debuginfo.nSize );
37340 return (u16)nSize;
37341 }
37342 #ifndef NDEBUG
37343 static u16 cellSize(MemPage *pPage, int iCell){
37344 return cellSizePtr(pPage, findCell(pPage, iCell));
 
 
37345 }
37346 #endif
 
 
 
 
 
37347
37348 #ifndef SQLITE_OMIT_AUTOVACUUM
37349 /*
37350 ** If the cell pCell, part of page pPage contains a pointer
37351 ** to an overflow page, insert an entry into the pointer-map
@@ -37120,17 +37488,17 @@
37488 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
37489 int size = get2byte(&data[pc+2]); /* Size of free slot */
37490 if( size>=nByte ){
37491 int x = size - nByte;
37492 if( x<4 ){
37493 /* Remove the slot from the free-list. Update the number of
37494 ** fragmented bytes within the page. */
37495 memcpy(&data[addr], &data[pc], 2);
37496 data[hdr+7] = (u8)(nFrag + x);
37497 }else{
37498 /* The slot remains on the free-list. Reduce its size to account
37499 ** for the portion used by the new allocation. */
37500 put2byte(&data[pc+2], x);
37501 }
37502 return pc + x;
37503 }
37504 }
@@ -37560,10 +37928,16 @@
37928 ** zFilename is the name of the database file. If zFilename is NULL
37929 ** a new database with a random name is created. This randomly named
37930 ** database file will be deleted when sqlite3BtreeClose() is called.
37931 ** If zFilename is ":memory:" then an in-memory database is created
37932 ** that is automatically destroyed when it is closed.
37933 **
37934 ** If the database is already opened in the same database connection
37935 ** and we are in shared cache mode, then the open will fail with an
37936 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
37937 ** objects in the same database connection since doing so will lead
37938 ** to problems with locking.
37939 */
37940 SQLITE_PRIVATE int sqlite3BtreeOpen(
37941 const char *zFilename, /* Name of the file containing the BTree database */
37942 sqlite3 *db, /* Associated database handle */
37943 Btree **ppBtree, /* Pointer to new Btree object written here */
@@ -37625,10 +37999,21 @@
37999 sqlite3_mutex_enter(mutexShared);
38000 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
38001 assert( pBt->nRef>0 );
38002 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
38003 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
38004 int iDb;
38005 for(iDb=db->nDb-1; iDb>=0; iDb--){
38006 Btree *pExisting = db->aDb[iDb].pBt;
38007 if( pExisting && pExisting->pBt==pBt ){
38008 sqlite3_mutex_leave(mutexShared);
38009 sqlite3_mutex_leave(mutexOpen);
38010 sqlite3_free(zFullPathname);
38011 sqlite3_free(p);
38012 return SQLITE_CONSTRAINT;
38013 }
38014 }
38015 p->pBt = pBt;
38016 pBt->nRef++;
38017 break;
38018 }
38019 }
@@ -37682,11 +38067,10 @@
38067 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
38068 pBt->pageSize = get2byte(&zDbHeader[16]);
38069 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
38070 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
38071 pBt->pageSize = 0;
 
38072 #ifndef SQLITE_OMIT_AUTOVACUUM
38073 /* If the magic name ":memory:" will create an in-memory database, then
38074 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
38075 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
38076 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
@@ -37704,13 +38088,14 @@
38088 #ifndef SQLITE_OMIT_AUTOVACUUM
38089 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
38090 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
38091 #endif
38092 }
38093 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
38094 if( rc ) goto btree_open_out;
38095 pBt->usableSize = pBt->pageSize - nReserve;
38096 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
 
38097
38098 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
38099 /* Add the new BtShared object to the linked list sharable BtShareds.
38100 */
38101 if( p->sharable ){
@@ -38150,11 +38535,12 @@
38535 */
38536 releasePage(pPage1);
38537 pBt->usableSize = (u16)usableSize;
38538 pBt->pageSize = (u16)pageSize;
38539 freeTempSpace(pBt);
38540 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
38541 if( rc ) goto page1_init_failed;
38542 return SQLITE_OK;
38543 }
38544 if( usableSize<500 ){
38545 goto page1_init_failed;
38546 }
@@ -38229,18 +38615,10 @@
38615 static void unlockBtreeIfUnused(BtShared *pBt){
38616 assert( sqlite3_mutex_held(pBt->mutex) );
38617 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
38618 if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
38619 assert( pBt->pPage1->aData );
 
 
 
 
 
 
 
 
38620 releasePage(pBt->pPage1);
38621 }
38622 pBt->pPage1 = 0;
38623 }
38624 }
@@ -38379,11 +38757,11 @@
38757
38758 if( rc==SQLITE_OK && wrflag ){
38759 if( pBt->readOnly ){
38760 rc = SQLITE_READONLY;
38761 }else{
38762 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
38763 if( rc==SQLITE_OK ){
38764 rc = newDatabase(pBt);
38765 }
38766 }
38767 }
@@ -38829,11 +39207,11 @@
39207 ** the journal. Then the contents of the journal are flushed out to
39208 ** the disk. After the journal is safely on oxide, the changes to the
39209 ** database are written into the database file and flushed to oxide.
39210 ** At the end of this call, the rollback journal still exists on the
39211 ** disk and we are still holding all locks, so the transaction has not
39212 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
39213 ** commit process.
39214 **
39215 ** This call is a no-op if no write-transaction is currently active on pBt.
39216 **
39217 ** Otherwise, sync the database file for the btree pBt. zMaster points to
@@ -38869,16 +39247,17 @@
39247
39248 /*
39249 ** Commit the transaction currently in progress.
39250 **
39251 ** This routine implements the second phase of a 2-phase commit. The
39252 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
39253 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
39254 ** routine did all the work of writing information out to disk and flushing the
39255 ** contents so that they are written onto the disk platter. All this
39256 ** routine has to do is delete or truncate or zero the header in the
39257 ** the rollback journal (which causes the transaction to commit) and
39258 ** drop locks.
39259 **
39260 ** This will release the write lock on the database file. If there
39261 ** are no active cursors, it also releases the read lock.
39262 */
39263 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
@@ -38913,11 +39292,11 @@
39292 if( 0==pBt->nTransaction ){
39293 pBt->inTransaction = TRANS_NONE;
39294 }
39295 }
39296
39297 /* Set the current transaction state to TRANS_NONE and unlock
39298 ** the pager if this call closed the only read or write transaction.
39299 */
39300 btreeClearHasContent(pBt);
39301 p->inTrans = TRANS_NONE;
39302 unlockBtreeIfUnused(pBt);
@@ -40069,20 +40448,35 @@
40448 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
40449 int rc;
40450
40451 assert( cursorHoldsMutex(pCur) );
40452 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
40453
40454 /* If the cursor already points to the last entry, this is a no-op. */
40455 if( CURSOR_VALID==pCur->eState && pCur->atLast ){
40456 #ifdef SQLITE_DEBUG
40457 /* This block serves to assert() that the cursor really does point
40458 ** to the last entry in the b-tree. */
40459 int ii;
40460 for(ii=0; ii<pCur->iPage; ii++){
40461 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
40462 }
40463 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
40464 assert( pCur->apPage[pCur->iPage]->leaf );
40465 #endif
40466 return SQLITE_OK;
40467 }
40468
40469 rc = moveToRoot(pCur);
40470 if( rc==SQLITE_OK ){
40471 if( CURSOR_INVALID==pCur->eState ){
40472 assert( pCur->apPage[pCur->iPage]->nCell==0 );
40473 *pRes = 1;
40474 }else{
40475 assert( pCur->eState==CURSOR_VALID );
40476 *pRes = 0;
40477 rc = moveToRightmost(pCur);
 
40478 pCur->atLast = rc==SQLITE_OK ?1:0;
40479 }
40480 }
40481 return rc;
40482 }
@@ -40169,18 +40563,17 @@
40563 pCur->aiIdx[pCur->iPage] = (u16)upr;
40564 }else{
40565 pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
40566 }
40567 for(;;){
40568 int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
40569 u8 *pCell; /* Pointer to current cell in pPage */
40570
40571 pCur->info.nSize = 0;
40572 pCell = findCell(pPage, idx) + pPage->childPtrSize;
40573 if( pPage->intKey ){
40574 i64 nCellKey;
 
40575 if( pPage->hasData ){
40576 u32 dummy;
40577 pCell += getVarint32(pCell, dummy);
40578 }
40579 getVarint(pCell, (u64*)&nCellKey);
@@ -40190,30 +40583,54 @@
40583 c = -1;
40584 }else{
40585 assert( nCellKey>intKey );
40586 c = +1;
40587 }
40588 pCur->validNKey = 1;
40589 pCur->info.nKey = nCellKey;
40590 }else{
40591 /* The maximum supported page-size is 32768 bytes. This means that
40592 ** the maximum number of record bytes stored on an index B-Tree
40593 ** page is at most 8198 bytes, which may be stored as a 2-byte
40594 ** varint. This information is used to attempt to avoid parsing
40595 ** the entire cell by checking for the cases where the record is
40596 ** stored entirely within the b-tree page by inspecting the first
40597 ** 2 bytes of the cell.
40598 */
40599 int nCell = pCell[0];
40600 if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
40601 /* This branch runs if the record-size field of the cell is a
40602 ** single byte varint and the record fits entirely on the main
40603 ** b-tree page. */
40604 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
40605 }else if( !(pCell[1] & 0x80)
40606 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
40607 ){
40608 /* The record-size field is a 2 byte varint and the record
40609 ** fits entirely on the main b-tree page. */
40610 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
40611 }else{
40612 /* The record flows over onto one or more overflow pages. In
40613 ** this case the whole cell needs to be parsed, a buffer allocated
40614 ** and accessPayload() used to retrieve the record into the
40615 ** buffer before VdbeRecordCompare() can be called. */
40616 void *pCellKey;
40617 u8 * const pCellBody = pCell - pPage->childPtrSize;
40618 sqlite3BtreeParseCellPtr(pPage, pCellBody, &pCur->info);
40619 nCell = (int)pCur->info.nKey;
40620 pCellKey = sqlite3Malloc( nCell );
40621 if( pCellKey==0 ){
40622 rc = SQLITE_NOMEM;
40623 goto moveto_finish;
40624 }
40625 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0, 0);
40626 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
40627 sqlite3_free(pCellKey);
40628 if( rc ) goto moveto_finish;
40629 }
40630 }
40631 if( c==0 ){
 
40632 if( pPage->intKey && !pPage->leaf ){
40633 lwr = idx;
40634 upr = lwr - 1;
40635 break;
40636 }else{
@@ -40226,11 +40643,10 @@
40643 lwr = idx+1;
40644 }else{
40645 upr = idx-1;
40646 }
40647 if( lwr>upr ){
 
40648 break;
40649 }
40650 pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
40651 }
40652 assert( lwr==upr+1 );
@@ -41187,11 +41603,11 @@
41603 ** the entry for the overflow page into the pointer map.
41604 */
41605 CellInfo info;
41606 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
41607 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
41608 if( info.iOverflow ){
41609 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
41610 rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
41611 if( rc!=SQLITE_OK ) return rc;
41612 }
41613 }
@@ -41210,43 +41626,36 @@
41626 int nCell, /* The number of cells to add to this page */
41627 u8 **apCell, /* Pointers to cell bodies */
41628 u16 *aSize /* Sizes of the cells */
41629 ){
41630 int i; /* Loop counter */
41631 u8 *pCellptr; /* Address of next cell pointer */
 
 
41632 int cellbody; /* Address of next cell body */
41633 u8 * const data = pPage->aData; /* Pointer to data for pPage */
41634 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
41635 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
41636
41637 assert( pPage->nOverflow==0 );
41638 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
41639 assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
41640 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
41641
41642 /* Check that the page has just been zeroed by zeroPage() */
 
 
41643 assert( pPage->nCell==0 );
41644 assert( get2byte(&data[hdr+5])==nUsable );
41645
41646 pCellptr = &data[pPage->cellOffset + nCell*2];
41647 cellbody = nUsable;
41648 for(i=nCell-1; i>=0; i--){
41649 pCellptr -= 2;
41650 cellbody -= aSize[i];
41651 put2byte(pCellptr, cellbody);
41652 memcpy(&data[cellbody], apCell[i], aSize[i]);
41653 }
41654 put2byte(&data[hdr+3], nCell);
41655 put2byte(&data[hdr+5], cellbody);
41656 pPage->nFree -= (nCell*2 + nUsable - cellbody);
 
 
 
 
 
 
 
 
 
 
 
41657 pPage->nCell = (u16)nCell;
41658 }
41659
41660 /*
41661 ** The following parameters determine how many adjacent pages get involved
@@ -42274,20 +42683,32 @@
42683 ** define what table the record should be inserted into. The cursor
42684 ** is left pointing at a random location.
42685 **
42686 ** For an INTKEY table, only the nKey value of the key is used. pKey is
42687 ** ignored. For a ZERODATA table, the pData and nData are both ignored.
42688 **
42689 ** If the seekResult parameter is non-zero, then a successful call to
42690 ** sqlite3BtreeMoveto() to seek cursor pCur to (pKey, nKey) has already
42691 ** been performed. seekResult is the search result returned (a negative
42692 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
42693 ** a positive value if pCur points at an etry that is larger than
42694 ** (pKey, nKey)).
42695 **
42696 ** If the seekResult parameter is 0, then cursor pCur may point to any
42697 ** entry or to no entry at all. In this case this function has to seek
42698 ** the cursor before the new key can be inserted.
42699 */
42700 SQLITE_PRIVATE int sqlite3BtreeInsert(
42701 BtCursor *pCur, /* Insert data into the table of this cursor */
42702 const void *pKey, i64 nKey, /* The key of the new record */
42703 const void *pData, int nData, /* The data of the new record */
42704 int nZero, /* Number of extra 0 bytes to append to data */
42705 int appendBias, /* True if this is likely an append */
42706 int seekResult /* Result of prior sqlite3BtreeMoveto() call */
42707 ){
42708 int rc;
42709 int loc = seekResult;
42710 int szNew;
42711 int idx;
42712 MemPage *pPage;
42713 Btree *p = pCur->pBtree;
42714 BtShared *pBt = p->pBt;
@@ -42306,16 +42727,25 @@
42727 }
42728 if( pCur->eState==CURSOR_FAULT ){
42729 return pCur->skip;
42730 }
42731
42732 /* Save the positions of any other cursors open on this table.
42733 **
42734 ** In some cases, the call to sqlite3BtreeMoveto() below is a no-op. For
42735 ** example, when inserting data into a table with auto-generated integer
42736 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
42737 ** integer key to use. It then calls this function to actually insert the
42738 ** data into the intkey B-Tree. In this case sqlite3BtreeMoveto() recognizes
42739 ** that the cursor is already where it needs to be and returns without
42740 ** doing any work. To avoid thwarting these optimizations, it is important
42741 ** not to clear the cursor here.
42742 */
42743 if(
42744 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) || (!loc &&
42745 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
42746 )){
42747 return rc;
42748 }
42749
42750 pPage = pCur->apPage[pCur->iPage];
42751 assert( pPage->intKey || nKey>=0 );
@@ -42357,21 +42787,46 @@
42787 pCur->validNKey = 0;
42788 }else{
42789 assert( pPage->leaf );
42790 }
42791 rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
42792 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
42793
42794 /* If no error has occured, call balance() to deal with any overflow and
42795 ** move the cursor to point at the root of the table (since balance may
42796 ** have rearranged the table in such a way as to invalidate BtCursor.apPage[]
42797 ** or BtCursor.aiIdx[]).
42798 **
42799 ** Except, if all of the following are true, do nothing:
42800 **
42801 ** * Inserting the new cell did not cause overflow,
42802 **
42803 ** * Before inserting the new cell the cursor was pointing at the
42804 ** largest key in an intkey B-Tree, and
42805 **
42806 ** * The key value associated with the new cell is now the largest
42807 ** in the B-Tree.
42808 **
42809 ** In this case the cursor can be safely left pointing at the (new)
42810 ** largest key value in the B-Tree. Doing so speeds up inserting a set
42811 ** of entries with increasing integer key values via a single cursor
42812 ** (comes up with "INSERT INTO ... SELECT ..." statements), as
42813 ** the next insert operation is not required to seek the cursor.
42814 */
42815 if( rc==SQLITE_OK
42816 && (pPage->nOverflow || !pCur->atLast || loc>=0 || !pCur->apPage[0]->intKey)
42817 ){
42818 rc = balance(pCur, 1);
42819 if( rc==SQLITE_OK ){
42820 moveToRoot(pCur);
42821 }
42822 }
42823
42824 /* Must make sure nOverflow is reset to zero even if the balance()
42825 ** fails. Internal data structure corruption will result otherwise. */
42826 pCur->apPage[pCur->iPage]->nOverflow = 0;
42827
 
 
 
42828 end_insert:
42829 return rc;
42830 }
42831
42832 /*
@@ -43199,11 +43654,11 @@
43654 u8 ePtrmapType;
43655 Pgno iPtrmapParent;
43656
43657 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
43658 if( rc!=SQLITE_OK ){
43659 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
43660 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
43661 return;
43662 }
43663
43664 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
@@ -43326,11 +43781,11 @@
43781 pBt = pCheck->pBt;
43782 usableSize = pBt->usableSize;
43783 if( iPage==0 ) return 0;
43784 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
43785 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
43786 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
43787 checkAppendMsg(pCheck, zContext,
43788 "unable to get the page. error code=%d", rc);
43789 return 0;
43790 }
43791 if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
@@ -44398,11 +44853,11 @@
44853 ** This file contains code use to manipulate "Mem" structure. A "Mem"
44854 ** stores a single value in the VDBE. Mem is an opaque structure visible
44855 ** only within the VDBE. Interface routines refer to a Mem using the
44856 ** name sqlite_value
44857 **
44858 ** $Id: vdbemem.c,v 1.144 2009/05/05 12:54:50 drh Exp $
44859 */
44860
44861 /*
44862 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
44863 ** P if required.
@@ -44651,20 +45106,22 @@
45106 ** invoking an external callback, free it now. Calling this function
45107 ** does not free any Mem.zMalloc buffer.
45108 */
45109 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
45110 assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
45111 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet) ){
45112 if( p->flags&MEM_Agg ){
45113 sqlite3VdbeMemFinalize(p, p->u.pDef);
45114 assert( (p->flags & MEM_Agg)==0 );
45115 sqlite3VdbeMemRelease(p);
45116 }else if( p->flags&MEM_Dyn && p->xDel ){
45117 assert( (p->flags&MEM_RowSet)==0 );
45118 p->xDel((void *)p->z);
45119 p->xDel = 0;
45120 }else if( p->flags&MEM_RowSet ){
45121 sqlite3RowSetClear(p->u.pRowSet);
45122 }
45123 }
45124 }
45125
45126 /*
45127 ** Release any memory held by the Mem. This may leave the Mem in an
@@ -45356,16 +45813,18 @@
45813
45814 if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
45815 zVal = sqlite3DbStrNDup(db, (char*)pExpr->token.z, pExpr->token.n);
45816 pVal = sqlite3ValueNew(db);
45817 if( !zVal || !pVal ) goto no_mem;
 
45818 sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
45819 if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
45820 sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
45821 }else{
45822 sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
45823 }
45824 if( enc!=SQLITE_UTF8 ){
45825 sqlite3VdbeChangeEncoding(pVal, enc);
45826 }
45827 }else if( op==TK_UMINUS ) {
45828 if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
45829 pVal->u.i = -1 * pVal->u.i;
45830 /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
@@ -45453,11 +45912,11 @@
45912 ** This file contains code used for creating, destroying, and populating
45913 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
45914 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
45915 ** But that file was getting too big so this subroutines were split out.
45916 **
45917 ** $Id: vdbeaux.c,v 1.457 2009/05/06 18:57:10 shane Exp $
45918 */
45919
45920
45921
45922 /*
@@ -46167,13 +46626,13 @@
46626 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
46627 **
46628 */
46629 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
46630 int mask;
46631 assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
46632 assert( i<(int)sizeof(p->btreeMask)*8 );
46633 mask = ((u32)1)<<i;
46634 if( (p->btreeMask & mask)==0 ){
46635 p->btreeMask |= mask;
46636 sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
46637 }
46638 }
@@ -47377,11 +47836,11 @@
47836 */
47837 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
47838 int i;
47839 for(i=0; i<pVdbeFunc->nAux; i++){
47840 struct AuxData *pAux = &pVdbeFunc->apAux[i];
47841 if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
47842 if( pAux->xDelete ){
47843 pAux->xDelete(pAux->pAux);
47844 }
47845 pAux->pAux = 0;
47846 }
@@ -47439,12 +47898,12 @@
47898 #endif
47899 assert( p->isTable );
47900 rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
47901 if( rc ) return rc;
47902 p->lastRowid = keyToInt(p->movetoTarget);
47903 p->rowidIsValid = ALWAYS(res==0) ?1:0;
47904 if( NEVER(res<0) ){
47905 rc = sqlite3BtreeNext(p->pCursor, &res);
47906 if( rc ) return rc;
47907 }
47908 #ifdef SQLITE_TEST
47909 sqlite3_search_count++;
@@ -47903,10 +48362,11 @@
48362
48363 pKeyInfo = pPKey2->pKeyInfo;
48364 mem1.enc = pKeyInfo->enc;
48365 mem1.db = pKeyInfo->db;
48366 mem1.flags = 0;
48367 mem1.u.i = 0; /* not needed, here to silence compiler warning */
48368 mem1.zMalloc = 0;
48369
48370 idx1 = getVarint32(aKey1, szHdr1);
48371 d1 = szHdr1;
48372 if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
@@ -47932,10 +48392,22 @@
48392 break;
48393 }
48394 i++;
48395 }
48396 if( mem1.zMalloc ) sqlite3VdbeMemRelease(&mem1);
48397
48398 /* If the PREFIX_SEARCH flag is set and all fields except the final
48399 ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
48400 ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
48401 ** This is used by the OP_IsUnique opcode.
48402 */
48403 if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
48404 assert( idx1==szHdr1 && rc );
48405 assert( mem1.flags & MEM_Int );
48406 pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
48407 pPKey2->rowid = mem1.u.i;
48408 }
48409
48410 if( rc==0 ){
48411 /* rc==0 here means that one of the keys ran out of fields and
48412 ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
48413 ** flag is set, then break the tie by treating key2 as larger.
@@ -48133,11 +48605,11 @@
48605 *************************************************************************
48606 **
48607 ** This file contains code use to implement APIs that are part of the
48608 ** VDBE.
48609 **
48610 ** $Id: vdbeapi.c,v 1.164 2009/04/27 18:46:06 drh Exp $
48611 */
48612
48613 #if 0 && defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
48614 /*
48615 ** The following structure contains pointers to the end points of a
@@ -48518,10 +48990,14 @@
48990 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
48991 sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
48992 }
48993 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
48994 pCtx->isError = errCode;
48995 if( pCtx->s.flags & MEM_Null ){
48996 sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
48997 SQLITE_UTF8, SQLITE_STATIC);
48998 }
48999 }
49000
49001 /* Force an SQLITE_TOOBIG error. */
49002 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
49003 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
@@ -49270,19 +49746,36 @@
49746 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
49747 }
49748 #endif /* SQLITE_OMIT_UTF16 */
49749 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
49750 int rc;
49751 switch( pValue->type ){
49752 case SQLITE_INTEGER: {
49753 rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
49754 break;
49755 }
49756 case SQLITE_FLOAT: {
49757 rc = sqlite3_bind_double(pStmt, i, pValue->r);
49758 break;
49759 }
49760 case SQLITE_BLOB: {
49761 if( pValue->flags & MEM_Zero ){
49762 rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
49763 }else{
49764 rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
49765 }
49766 break;
49767 }
49768 case SQLITE_TEXT: {
49769 rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
49770 pValue->enc);
49771 break;
49772 }
49773 default: {
49774 rc = sqlite3_bind_null(pStmt, i);
49775 break;
49776 }
49777 }
49778 return rc;
49779 }
49780 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
49781 int rc;
@@ -49491,11 +49984,11 @@
49984 ** documentation, headers files, or other derived files. The formatting
49985 ** of the code in this file is, therefore, important. See other comments
49986 ** in this file for details. If in doubt, do not deviate from existing
49987 ** commenting and indentation practices when changing or adding code.
49988 **
49989 ** $Id: vdbe.c,v 1.842 2009/05/06 18:57:10 shane Exp $
49990 */
49991
49992 /*
49993 ** The following global variable is incremented every time a cursor
49994 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
@@ -49874,10 +50367,12 @@
50367 fprintf(out, " si:%lld", p->u.i);
50368 }else if( p->flags & MEM_Int ){
50369 fprintf(out, " i:%lld", p->u.i);
50370 }else if( p->flags & MEM_Real ){
50371 fprintf(out, " r:%g", p->r);
50372 }else if( p->flags & MEM_RowSet ){
50373 fprintf(out, " (rowset)");
50374 }else{
50375 char zBuf[200];
50376 sqlite3VdbeMemPrettyPrint(p, zBuf);
50377 fprintf(out, " ");
50378 fprintf(out, "%s", zBuf);
@@ -51999,11 +52494,11 @@
52494 if( db->autoCommit ){
52495 db->autoCommit = 0;
52496 db->isTransactionSavepoint = 1;
52497 }else{
52498 db->nSavepoint++;
52499 }
52500
52501 /* Link the new savepoint into the database handle's list. */
52502 pNew->pNext = db->pSavepoint;
52503 db->pSavepoint = pNew;
52504 }
@@ -52873,107 +53368,86 @@
53368 break;
53369 }
53370
53371 /* Opcode: IsUnique P1 P2 P3 P4 *
53372 **
53373 ** Cursor P1 is open on an index. So it has no data and its key consists
53374 ** of a record generated by OP_MakeRecord where the last field is the
 
 
 
 
53375 ** rowid of the entry that the index refers to.
53376 **
53377 ** The P3 register contains an integer record number. Call this record
53378 ** number R. Register P4 is the first in a set of N contiguous registers
53379 ** that make up an unpacked index key that can be used with cursor P1.
53380 ** The value of N can be inferred from the cursor. N includes the rowid
53381 ** value appended to the end of the index record. This rowid value may
53382 ** or may not be the same as R.
53383 **
53384 ** If any of the N registers beginning with register P4 contains a NULL
53385 ** value, jump immediately to P2.
53386 **
53387 ** Otherwise, this instruction checks if cursor P1 contains an entry
53388 ** where the first (N-1) fields match but the rowid value at the end
53389 ** of the index entry is not R. If there is no such entry, control jumps
53390 ** to instruction P2. Otherwise, the rowid of the conflicting index
53391 ** entry is copied to register P3 and control falls through to the next
53392 ** instruction.
53393 **
53394 ** See also: NotFound, NotExists, Found
53395 */
53396 case OP_IsUnique: { /* jump, in3 */
53397 u16 ii;
53398 VdbeCursor *pCx;
53399 BtCursor *pCrsr;
53400 u16 nField;
53401 Mem *aMem = &p->aMem[pOp->p4.i];
53402
53403 /* Assert that the values of parameters P1 and P4 are in range. */
 
53404 assert( pOp->p4type==P4_INT32 );
53405 assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
53406 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
53407
53408 /* Find the index cursor. */
53409 pCx = p->apCsr[pOp->p1];
53410 assert( pCx->deferredMoveto==0 );
53411 pCx->seekResult = 0;
53412 pCx->cacheStatus = CACHE_STALE;
53413 pCrsr = pCx->pCursor;
53414
53415 /* If any of the values are NULL, take the jump. */
53416 nField = pCx->pKeyInfo->nField;
53417 for(ii=0; ii<nField; ii++){
53418 if( aMem[ii].flags & MEM_Null ){
53419 pc = pOp->p2 - 1;
53420 pCrsr = 0;
53421 break;
53422 }
53423 }
53424 assert( (aMem[nField].flags & MEM_Null)==0 );
53425
53426 if( pCrsr!=0 ){
53427 UnpackedRecord r; /* B-Tree index search key */
53428 i64 R; /* Rowid stored in register P3 */
53429
53430 /* Populate the index search key. */
53431 r.pKeyInfo = pCx->pKeyInfo;
53432 r.nField = nField + 1;
53433 r.flags = UNPACKED_PREFIX_SEARCH;
53434 r.aMem = aMem;
53435
53436 /* Extract the value of R from register P3. */
53437 sqlite3VdbeMemIntegerify(pIn3);
53438 R = pIn3->u.i;
53439
53440 /* Search the B-Tree index. If no conflicting record is found, jump
53441 ** to P2. Otherwise, copy the rowid of the conflicting record to
53442 ** register P3 and fall through to the next instruction. */
53443 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &pCx->seekResult);
53444 if( (r.flags & UNPACKED_PREFIX_SEARCH) || r.rowid==R ){
53445 pc = pOp->p2 - 1;
53446 }else{
53447 pIn3->u.i = r.rowid;
53448 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53449 }
53450 break;
53451 }
53452
53453 /* Opcode: NotExists P1 P2 P3 * *
@@ -53000,26 +53474,29 @@
53474 int res = 0;
53475 u64 iKey;
53476 assert( pIn3->flags & MEM_Int );
53477 assert( p->apCsr[i]->isTable );
53478 iKey = intToKey(pIn3->u.i);
53479 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
53480 pC->lastRowid = pIn3->u.i;
53481 pC->rowidIsValid = res==0 ?1:0;
53482 pC->nullRow = 0;
53483 pC->cacheStatus = CACHE_STALE;
53484 pC->deferredMoveto = 0;
53485 if( res!=0 ){
53486 pc = pOp->p2 - 1;
53487 assert( pC->rowidIsValid==0 );
53488 }
53489 pC->seekResult = res;
53490 }else if( !pC->pseudoTable ){
53491 /* This happens when an attempt to open a read cursor on the
53492 ** sqlite_master table returns SQLITE_EMPTY.
53493 */
53494 assert( pC->isTable );
53495 pc = pOp->p2 - 1;
53496 assert( pC->rowidIsValid==0 );
53497 pC->seekResult = 0;
53498 }
53499 break;
53500 }
53501
53502 /* Opcode: Sequence P1 P2 * * *
@@ -53258,19 +53735,21 @@
53735 pC->pData[pC->nData+1] = 0;
53736 }
53737 pC->nullRow = 0;
53738 }else{
53739 int nZero;
53740 int seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
53741 if( pData->flags & MEM_Zero ){
53742 nZero = pData->u.nZero;
53743 }else{
53744 nZero = 0;
53745 }
53746 sqlite3BtreeSetCachedRowid(pC->pCursor, 0);
53747 rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
53748 pData->z, pData->n, nZero,
53749 pOp->p5 & OPFLAG_APPEND, seekResult
53750 );
53751 }
53752
53753 pC->rowidIsValid = 0;
53754 pC->deferredMoveto = 0;
53755 pC->cacheStatus = CACHE_STALE;
@@ -53430,32 +53909,54 @@
53909
53910 /* Opcode: Rowid P1 P2 * * *
53911 **
53912 ** Store in register P2 an integer which is the key of the table entry that
53913 ** P1 is currently point to.
53914 **
53915 ** P1 can be either an ordinary table or a virtual table. There used to
53916 ** be a separate OP_VRowid opcode for use with virtual tables, but this
53917 ** one opcode now works for both table types.
53918 */
53919 case OP_Rowid: { /* out2-prerelease */
53920 int i = pOp->p1;
53921 VdbeCursor *pC;
53922 i64 v;
53923
53924 assert( i>=0 && i<p->nCursor );
53925 pC = p->apCsr[i];
53926 assert( pC!=0 );
53927 if( pC->nullRow ){
53928 /* Do nothing so that reg[P2] remains NULL */
53929 break;
53930 }else if( pC->deferredMoveto ){
53931 v = pC->movetoTarget;
53932 }else if( pC->pseudoTable ){
53933 v = keyToInt(pC->iKey);
53934 #ifndef SQLITE_OMIT_VIRTUALTABLE
53935 }else if( pC->pVtabCursor ){
53936 sqlite3_vtab *pVtab;
53937 const sqlite3_module *pModule;
53938 pVtab = pC->pVtabCursor->pVtab;
53939 pModule = pVtab->pModule;
53940 assert( pModule->xRowid );
53941 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
53942 rc = pModule->xRowid(pC->pVtabCursor, &v);
53943 sqlite3DbFree(db, p->zErrMsg);
53944 p->zErrMsg = pVtab->zErrMsg;
53945 pVtab->zErrMsg = 0;
53946 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
53947 #endif /* SQLITE_OMIT_VIRTUALTABLE */
53948 }else{
53949 rc = sqlite3VdbeCursorMoveto(pC);
53950 if( rc ) goto abort_due_to_error;
53951 if( pC->rowidIsValid ){
53952 v = pC->lastRowid;
53953 }else{
53954 assert( pC->pCursor!=0 );
53955 sqlite3BtreeKeySize(pC->pCursor, &v);
53956 v = keyToInt(v);
53957 }
53958 }
53959 pOut->u.i = v;
53960 MemSetTypeFlag(pOut, MEM_Int);
53961 break;
53962 }
@@ -53615,11 +54116,11 @@
54116 }
54117 pC->rowidIsValid = 0;
54118 break;
54119 }
54120
54121 /* Opcode: IdxInsert P1 P2 P3 * P5
54122 **
54123 ** Register P2 holds a SQL index key made using the
54124 ** MakeRecord instructions. This opcode writes that key
54125 ** into the index P1. Data for the entry is nil.
54126 **
@@ -53640,11 +54141,13 @@
54141 assert( pC->isTable==0 );
54142 rc = ExpandBlob(pIn2);
54143 if( rc==SQLITE_OK ){
54144 int nKey = pIn2->n;
54145 const char *zKey = pIn2->z;
54146 rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3,
54147 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
54148 );
54149 assert( pC->deferredMoveto==0 );
54150 pC->cacheStatus = CACHE_STALE;
54151 }
54152 }
54153 break;
@@ -54138,10 +54641,63 @@
54641 sqlite3VdbeMemSetInt64(pOut, val);
54642 }
54643 break;
54644 }
54645
54646 /* Opcode: RowSetTest P1 P2 P3 P4
54647 **
54648 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
54649 ** contains a RowSet object and that RowSet object contains
54650 ** the value held in P3, jump to register P2. Otherwise, insert the
54651 ** integer in P3 into the RowSet and continue on to the
54652 ** next opcode.
54653 **
54654 ** The RowSet object is optimized for the case where successive sets
54655 ** of integers, where each set contains no duplicates. Each set
54656 ** of values is identified by a unique P4 value. The first set
54657 ** must have P4==0, the final set P4=-1. P4 must be either -1 or
54658 ** non-negative. For non-negative values of P4 only the lower 4
54659 ** bits are significant.
54660 **
54661 ** This allows optimizations: (a) when P4==0 there is no need to test
54662 ** the rowset object for P3, as it is guaranteed not to contain it,
54663 ** (b) when P4==-1 there is no need to insert the value, as it will
54664 ** never be tested for, and (c) when a value that is part of set X is
54665 ** inserted, there is no need to search to see if the same value was
54666 ** previously inserted as part of set X (only if it was previously
54667 ** inserted as part of some other set).
54668 */
54669 case OP_RowSetTest: { /* jump, in1, in3 */
54670 int iSet = pOp->p4.i;
54671 assert( pIn3->flags&MEM_Int );
54672
54673 /* If there is anything other than a rowset object in memory cell P1,
54674 ** delete it now and initialize P1 with an empty rowset
54675 */
54676 if( (pIn1->flags & MEM_RowSet)==0 ){
54677 sqlite3VdbeMemSetRowSet(pIn1);
54678 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
54679 }
54680
54681 assert( pOp->p4type==P4_INT32 );
54682 assert( iSet==-1 || iSet>=0 );
54683 if( iSet ){
54684 int exists;
54685 exists = sqlite3RowSetTest(pIn1->u.pRowSet,
54686 (u8)(iSet>=0 ? iSet & 0xf : 0xff),
54687 pIn3->u.i);
54688 if( exists ){
54689 pc = pOp->p2 - 1;
54690 break;
54691 }
54692 }
54693 if( iSet>=0 ){
54694 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
54695 }
54696 break;
54697 }
54698
54699
54700 #ifndef SQLITE_OMIT_TRIGGER
54701 /* Opcode: ContextPush * * *
54702 **
54703 ** Save the current Vdbe context such that it can be restored by a ContextPop
@@ -54569,41 +55125,10 @@
55125 }
55126 pCur->nullRow = 0;
55127
55128 break;
55129 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55130 #endif /* SQLITE_OMIT_VIRTUALTABLE */
55131
55132 #ifndef SQLITE_OMIT_VIRTUALTABLE
55133 /* Opcode: VColumn P1 P2 P3 * *
55134 **
@@ -55569,11 +56094,11 @@
56094 **
56095 ** This file contains code use to implement an in-memory rollback journal.
56096 ** The in-memory rollback journal is used to journal transactions for
56097 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
56098 **
56099 ** @(#) $Id: memjournal.c,v 1.12 2009/05/04 11:42:30 danielk1977 Exp $
56100 */
56101
56102 /* Forward references to internal structures */
56103 typedef struct MemJournal MemJournal;
56104 typedef struct FilePoint FilePoint;
@@ -55683,11 +56208,11 @@
56208 u8 *zWrite = (u8 *)zBuf;
56209
56210 /* An in-memory journal file should only ever be appended to. Random
56211 ** access writes are not required by sqlite.
56212 */
56213 assert( iOfst==p->endpoint.iOffset );
56214 UNUSED_PARAMETER(iOfst);
56215
56216 while( nWrite>0 ){
56217 FileChunk *pChunk = p->endpoint.pChunk;
56218 int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
@@ -55969,11 +56494,11 @@
56494 **
56495 ** This file contains routines used for walking the parser tree and
56496 ** resolve all identifiers by associating them with a particular
56497 ** table and column.
56498 **
56499 ** $Id: resolve.c,v 1.22 2009/05/05 15:46:43 drh Exp $
56500 */
56501
56502 /*
56503 ** Turn the pExpr expression into an alias for the iCol-th column of the
56504 ** result set in pEList.
@@ -56200,11 +56725,15 @@
56725 pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
56726 pExpr->pTab = pTab;
56727 if( iCol>=0 ){
56728 testcase( iCol==31 );
56729 testcase( iCol==32 );
56730 if( iCol>=32 ){
56731 *piColMask = 0xffffffff;
56732 }else{
56733 *piColMask |= ((u32)1)<<iCol;
56734 }
56735 }
56736 break;
56737 }
56738 }
56739 }
@@ -56271,11 +56800,11 @@
56800 ** pExpr.
56801 **
56802 ** Because no reference was made to outer contexts, the pNC->nRef
56803 ** fields are not changed in any context.
56804 */
56805 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
56806 sqlite3DbFree(db, zCol);
56807 pExpr->op = TK_STRING;
56808 pExpr->pTab = 0;
56809 return 0;
56810 }
@@ -57139,11 +57668,11 @@
57668 **
57669 *************************************************************************
57670 ** This file contains routines used for analyzing expressions and
57671 ** for generating VDBE code that evaluates expressions in SQLite.
57672 **
57673 ** $Id: expr.c,v 1.432 2009/05/06 18:57:10 shane Exp $
57674 */
57675
57676 /*
57677 ** Return the 'affinity' of the expression pExpr if any.
57678 **
@@ -57533,25 +58062,22 @@
58062 pNew->span.z = (u8*)"";
58063 if( pToken ){
58064 int c;
58065 assert( pToken->dyn==0 );
58066 pNew->span = *pToken;
 
 
 
 
 
 
 
58067 if( pToken->n>=2
58068 && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
58069 sqlite3TokenCopy(db, &pNew->token, pToken);
58070 if( pNew->token.z ){
58071 pNew->token.n = sqlite3Dequote((char*)pNew->token.z);
58072 assert( pNew->token.n==(unsigned)sqlite3Strlen30((char*)pNew->token.z) );
58073 }
58074 if( c=='"' ) pNew->flags |= EP_DblQuoted;
58075 }else{
58076 pNew->token = *pToken;
 
 
58077 }
58078 pNew->token.quoted = 0;
58079 }else if( pLeft ){
58080 if( pRight ){
58081 if( pRight->span.dyn==0 && pLeft->span.dyn==0 ){
58082 sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
58083 }
@@ -57784,22 +58310,10 @@
58310 if( p==0 ) return;
58311 sqlite3ExprClear(db, p);
58312 sqlite3DbFree(db, p);
58313 }
58314
 
 
 
 
 
 
 
 
 
 
 
 
58315 /*
58316 ** Return the number of bytes allocated for the expression structure
58317 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
58318 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
58319 */
@@ -58589,11 +59103,11 @@
59103 int isRowid
59104 ){
59105 int testAddr = 0; /* One-time test address */
59106 Vdbe *v = sqlite3GetVdbe(pParse);
59107 if( v==0 ) return;
59108 sqlite3ExprCachePush(pParse);
59109
59110 /* This code must be run in its entirety every time it is encountered
59111 ** if any of the following is true:
59112 **
59113 ** * The right-hand side is a correlated subquery
@@ -58696,15 +59210,11 @@
59210 sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
59211 testAddr = 0;
59212 }
59213
59214 /* Evaluate the expression and insert it into the temp table */
 
59215 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
 
 
 
59216 if( isRowid ){
59217 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, sqlite3VdbeCurrentAddr(v)+2);
59218 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
59219 }else{
59220 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
@@ -58725,11 +59235,11 @@
59235 case TK_SELECT: {
59236 /* This has to be a scalar SELECT. Generate code to put the
59237 ** value of this select in a memory cell and record the number
59238 ** of the memory cell in iColumn.
59239 */
59240 static const Token one = { (u8*)"1", 0, 0, 1 };
59241 Select *pSel;
59242 SelectDest dest;
59243
59244 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
59245 pSel = pExpr->x.pSelect;
@@ -58754,10 +59264,11 @@
59264 }
59265
59266 if( testAddr ){
59267 sqlite3VdbeJumpHere(v, testAddr-1);
59268 }
59269 sqlite3ExprCachePop(pParse, 1);
59270
59271 return;
59272 }
59273 #endif /* SQLITE_OMIT_SUBQUERY */
59274
@@ -58831,10 +59342,124 @@
59342 codeReal(v, z, n, negFlag, iMem);
59343 }
59344 }
59345 }
59346
59347 /*
59348 ** Clear a cache entry.
59349 */
59350 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
59351 if( p->tempReg ){
59352 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
59353 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
59354 }
59355 p->tempReg = 0;
59356 }
59357 }
59358
59359
59360 /*
59361 ** Record in the column cache that a particular column from a
59362 ** particular table is stored in a particular register.
59363 */
59364 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
59365 int i;
59366 int minLru;
59367 int idxLru;
59368 struct yColCache *p;
59369
59370 /* First replace any existing entry */
59371 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59372 if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
59373 cacheEntryClear(pParse, p);
59374 p->iLevel = pParse->iCacheLevel;
59375 p->iReg = iReg;
59376 p->affChange = 0;
59377 p->lru = pParse->iCacheCnt++;
59378 return;
59379 }
59380 }
59381 if( iReg<=0 ) return;
59382
59383 /* Find an empty slot and replace it */
59384 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59385 if( p->iReg==0 ){
59386 p->iLevel = pParse->iCacheLevel;
59387 p->iTable = iTab;
59388 p->iColumn = iCol;
59389 p->iReg = iReg;
59390 p->affChange = 0;
59391 p->tempReg = 0;
59392 p->lru = pParse->iCacheCnt++;
59393 return;
59394 }
59395 }
59396
59397 /* Replace the last recently used */
59398 minLru = 0x7fffffff;
59399 idxLru = -1;
59400 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59401 if( p->lru<minLru ){
59402 idxLru = i;
59403 minLru = p->lru;
59404 }
59405 }
59406 if( idxLru>=0 ){
59407 p = &pParse->aColCache[idxLru];
59408 p->iLevel = pParse->iCacheLevel;
59409 p->iTable = iTab;
59410 p->iColumn = iCol;
59411 p->iReg = iReg;
59412 p->affChange = 0;
59413 p->tempReg = 0;
59414 p->lru = pParse->iCacheCnt++;
59415 return;
59416 }
59417 }
59418
59419 /*
59420 ** Indicate that a register is being overwritten. Purge the register
59421 ** from the column cache.
59422 */
59423 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg){
59424 int i;
59425 struct yColCache *p;
59426 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59427 if( p->iReg==iReg ){
59428 cacheEntryClear(pParse, p);
59429 p->iReg = 0;
59430 }
59431 }
59432 }
59433
59434 /*
59435 ** Remember the current column cache context. Any new entries added
59436 ** added to the column cache after this call are removed when the
59437 ** corresponding pop occurs.
59438 */
59439 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
59440 pParse->iCacheLevel++;
59441 }
59442
59443 /*
59444 ** Remove from the column cache any entries that were added since the
59445 ** the previous N Push operations. In other words, restore the cache
59446 ** to the state it was in N Pushes ago.
59447 */
59448 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
59449 int i;
59450 struct yColCache *p;
59451 assert( N>0 );
59452 assert( pParse->iCacheLevel>=N );
59453 pParse->iCacheLevel -= N;
59454 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59455 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
59456 cacheEntryClear(pParse, p);
59457 p->iReg = 0;
59458 }
59459 }
59460 }
59461
59462 /*
59463 ** Generate code that will extract the iColumn-th column from
59464 ** table pTab and store the column value in a register. An effort
59465 ** is made to store the column value in register iReg, but this is
@@ -58859,24 +59484,25 @@
59484 ){
59485 Vdbe *v = pParse->pVdbe;
59486 int i;
59487 struct yColCache *p;
59488
59489 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59490 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn
59491 && (!p->affChange || allowAffChng) ){
59492 #if 0
59493 sqlite3VdbeAddOp0(v, OP_Noop);
59494 VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
59495 #endif
59496 p->lru = pParse->iCacheCnt++;
59497 p->tempReg = 0; /* This pins the register, but also leaks it */
59498 return p->iReg;
59499 }
59500 }
59501 assert( v!=0 );
59502 if( iColumn<0 ){
59503 sqlite3VdbeAddOp2(v, OP_Rowid, iTable, iReg);
 
59504 }else if( pTab==0 ){
59505 sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
59506 }else{
59507 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
59508 sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
@@ -58885,41 +59511,25 @@
59511 if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
59512 sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
59513 }
59514 #endif
59515 }
59516 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
 
 
 
 
 
 
 
 
 
 
 
59517 return iReg;
59518 }
59519
59520 /*
59521 ** Clear all column cache entries.
 
59522 */
59523 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
59524 int i;
59525 struct yColCache *p;
59526
59527 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59528 if( p->iReg ){
59529 cacheEntryClear(pParse, p);
59530 p->iReg = 0;
 
 
 
 
59531 }
59532 }
59533 }
59534
59535 /*
@@ -58927,14 +59537,15 @@
59537 ** registers starting with iStart.
59538 */
59539 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
59540 int iEnd = iStart + iCount - 1;
59541 int i;
59542 struct yColCache *p;
59543 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59544 int r = p->iReg;
59545 if( r>=iStart && r<=iEnd ){
59546 p->affChange = 1;
59547 }
59548 }
59549 }
59550
59551 /*
@@ -58941,16 +59552,17 @@
59552 ** Generate code to move content from registers iFrom...iFrom+nReg-1
59553 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
59554 */
59555 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
59556 int i;
59557 struct yColCache *p;
59558 if( iFrom==iTo ) return;
59559 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
59560 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59561 int x = p->iReg;
59562 if( x>=iFrom && x<iFrom+nReg ){
59563 p->iReg += iTo-iFrom;
59564 }
59565 }
59566 }
59567
59568 /*
@@ -58969,36 +59581,18 @@
59581 ** Return true if any register in the range iFrom..iTo (inclusive)
59582 ** is used as part of the column cache.
59583 */
59584 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
59585 int i;
59586 struct yColCache *p;
59587 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
59588 int r = p->iReg;
59589 if( r>=iFrom && r<=iTo ) return 1;
59590 }
59591 return 0;
59592 }
59593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59594 /*
59595 ** If the last instruction coded is an ephemeral copy of any of
59596 ** the registers in the nReg registers beginning with iReg, then
59597 ** convert the last instruction from OP_SCopy to OP_Copy.
59598 */
@@ -59032,10 +59626,11 @@
59626 ** pParse->aAlias[iAlias-1] records the register number where the value
59627 ** of the iAlias-th alias is stored. If zero, that means that the
59628 ** alias has not yet been computed.
59629 */
59630 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
59631 #if 0
59632 sqlite3 *db = pParse->db;
59633 int iReg;
59634 if( pParse->nAliasAlloc<pParse->nAlias ){
59635 pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
59636 sizeof(pParse->aAlias[0])*pParse->nAlias );
@@ -59046,19 +59641,23 @@
59641 pParse->nAliasAlloc = pParse->nAlias;
59642 }
59643 assert( iAlias>0 && iAlias<=pParse->nAlias );
59644 iReg = pParse->aAlias[iAlias-1];
59645 if( iReg==0 ){
59646 if( pParse->iCacheLevel>0 ){
59647 iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
59648 }else{
59649 iReg = ++pParse->nMem;
59650 sqlite3ExprCode(pParse, pExpr, iReg);
59651 pParse->aAlias[iAlias-1] = iReg;
59652 }
59653 }
59654 return iReg;
59655 #else
59656 UNUSED_PARAMETER(iAlias);
59657 return sqlite3ExprCodeTarget(pParse, pExpr, target);
59658 #endif
59659 }
59660
59661 /*
59662 ** Generate code into the current Vdbe to evaluate the given
59663 ** expression. Attempt to store the results in register "target".
@@ -59124,12 +59723,11 @@
59723 case TK_FLOAT: {
59724 codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
59725 break;
59726 }
59727 case TK_STRING: {
59728 sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0,
 
59729 (char*)pExpr->token.z, pExpr->token.n);
59730 break;
59731 }
59732 case TK_NULL: {
59733 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
@@ -59434,13 +60032,12 @@
60032
60033
60034 /* Code the <expr> from "<expr> IN (...)". The temporary table
60035 ** pExpr->iTable contains the values that make up the (...) set.
60036 */
60037 sqlite3ExprCachePush(pParse);
60038 sqlite3ExprCode(pParse, pExpr->pLeft, target);
 
60039 j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target);
60040 if( eType==IN_INDEX_ROWID ){
60041 j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target);
60042 j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target);
60043 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
@@ -59497,10 +60094,11 @@
60094 sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target);
60095 }
60096 }
60097 sqlite3VdbeJumpHere(v, j2);
60098 sqlite3VdbeJumpHere(v, j5);
60099 sqlite3ExprCachePop(pParse, 1);
60100 VdbeComment((v, "end IN expr r%d", target));
60101 break;
60102 }
60103 #endif
60104 /*
@@ -59573,10 +60171,11 @@
60171 struct ExprList_item *aListelem; /* Array of WHEN terms */
60172 Expr opCompare; /* The X==Ei expression */
60173 Expr cacheX; /* Cached expression X */
60174 Expr *pX; /* The X expression */
60175 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
60176 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
60177
60178 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
60179 assert((pExpr->x.pList->nExpr % 2) == 0);
60180 assert(pExpr->x.pList->nExpr > 0);
60181 pEList = pExpr->x.pList;
@@ -59591,12 +60190,12 @@
60190 cacheX.op = TK_REGISTER;
60191 opCompare.op = TK_EQ;
60192 opCompare.pLeft = &cacheX;
60193 pTest = &opCompare;
60194 }
 
60195 for(i=0; i<nExpr; i=i+2){
60196 sqlite3ExprCachePush(pParse);
60197 if( pX ){
60198 assert( pTest!=0 );
60199 opCompare.pRight = aListelem[i].pExpr;
60200 }else{
60201 pTest = aListelem[i].pExpr;
@@ -59606,20 +60205,23 @@
60205 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
60206 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
60207 testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
60208 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
60209 sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
60210 sqlite3ExprCachePop(pParse, 1);
60211 sqlite3VdbeResolveLabel(v, nextCase);
60212 }
60213 if( pExpr->pRight ){
60214 sqlite3ExprCachePush(pParse);
60215 sqlite3ExprCode(pParse, pExpr->pRight, target);
60216 sqlite3ExprCachePop(pParse, 1);
60217 }else{
60218 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
60219 }
60220 assert( db->mallocFailed || pParse->nErr>0
60221 || pParse->iCacheLevel==iCacheLevel );
60222 sqlite3VdbeResolveLabel(v, endLabel);
 
 
60223 break;
60224 }
60225 #ifndef SQLITE_OMIT_TRIGGER
60226 case TK_RAISE: {
60227 if( !pParse->trigStack ){
@@ -59629,11 +60231,10 @@
60231 }
60232 if( pExpr->affinity!=OE_Ignore ){
60233 assert( pExpr->affinity==OE_Rollback ||
60234 pExpr->affinity == OE_Abort ||
60235 pExpr->affinity == OE_Fail );
 
60236 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->affinity, 0,
60237 (char*)pExpr->token.z, pExpr->token.n);
60238 } else {
60239 assert( pExpr->affinity == OE_Ignore );
60240 sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
@@ -59890,27 +60491,21 @@
60491 op = pExpr->op;
60492 switch( op ){
60493 case TK_AND: {
60494 int d2 = sqlite3VdbeMakeLabel(v);
60495 testcase( jumpIfNull==0 );
60496 sqlite3ExprCachePush(pParse);
60497 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
 
60498 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
 
 
60499 sqlite3VdbeResolveLabel(v, d2);
60500 sqlite3ExprCachePop(pParse, 1);
60501 break;
60502 }
60503 case TK_OR: {
60504 testcase( jumpIfNull==0 );
 
60505 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
 
60506 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
 
 
60507 break;
60508 }
60509 case TK_NOT: {
60510 testcase( jumpIfNull==0 );
60511 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
@@ -60050,28 +60645,22 @@
60645 assert( pExpr->op!=TK_GE || op==OP_Lt );
60646
60647 switch( pExpr->op ){
60648 case TK_AND: {
60649 testcase( jumpIfNull==0 );
 
60650 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
 
60651 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
 
 
60652 break;
60653 }
60654 case TK_OR: {
60655 int d2 = sqlite3VdbeMakeLabel(v);
60656 testcase( jumpIfNull==0 );
60657 sqlite3ExprCachePush(pParse);
60658 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
 
60659 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
 
 
60660 sqlite3VdbeResolveLabel(v, d2);
60661 sqlite3ExprCachePop(pParse, 1);
60662 break;
60663 }
60664 case TK_NOT: {
60665 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
60666 break;
@@ -60403,21 +60992,37 @@
60992 }
60993 }
60994 }
60995
60996 /*
60997 ** Allocate a single new register for use to hold some intermediate result.
60998 */
60999 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
61000 if( pParse->nTempReg==0 ){
61001 return ++pParse->nMem;
61002 }
61003 return pParse->aTempReg[--pParse->nTempReg];
61004 }
61005
61006 /*
61007 ** Deallocate a register, making available for reuse for some other
61008 ** purpose.
61009 **
61010 ** If a register is currently being used by the column cache, then
61011 ** the dallocation is deferred until the column cache line that uses
61012 ** the register becomes stale.
61013 */
61014 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
61015 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
61016 int i;
61017 struct yColCache *p;
61018 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
61019 if( p->iReg==iReg ){
61020 p->tempReg = 1;
61021 return;
61022 }
61023 }
61024 pParse->aTempReg[pParse->nTempReg++] = iReg;
61025 }
61026 }
61027
61028 /*
@@ -60457,11 +61062,11 @@
61062 **
61063 *************************************************************************
61064 ** This file contains C code routines that used to generate VDBE code
61065 ** that implements the ALTER TABLE command.
61066 **
61067 ** $Id: alter.c,v 1.57 2009/04/16 16:30:18 drh Exp $
61068 */
61069
61070 /*
61071 ** The code in this file only exists if we are not omitting the
61072 ** ALTER TABLE logic from the build.
@@ -60669,11 +61274,11 @@
61274 #ifndef SQLITE_OMIT_TRIGGER
61275 Trigger *pTrig;
61276 #endif
61277
61278 v = sqlite3GetVdbe(pParse);
61279 if( NEVER(v==0) ) return;
61280 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
61281 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
61282 assert( iDb>=0 );
61283
61284 #ifndef SQLITE_OMIT_TRIGGER
@@ -60723,11 +61328,11 @@
61328 #ifndef SQLITE_OMIT_TRIGGER
61329 char *zWhere = 0; /* Where clause to locate temp triggers */
61330 #endif
61331 int isVirtualRename = 0; /* True if this is a v-table with an xRename() */
61332
61333 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
61334 assert( pSrc->nSrc==1 );
61335 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
61336
61337 pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
61338 if( !pTab ) goto exit_rename_table;
@@ -60956,11 +61561,11 @@
61561
61562 /* Modify the CREATE TABLE statement. */
61563 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
61564 if( zCol ){
61565 char *zEnd = &zCol[pColDef->n-1];
61566 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
61567 *zEnd-- = '\0';
61568 }
61569 sqlite3NestedParse(pParse,
61570 "UPDATE \"%w\".%s SET "
61571 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
@@ -61087,11 +61692,11 @@
61692 ** May you share freely, never taking more than you give.
61693 **
61694 *************************************************************************
61695 ** This file contains code associated with the ANALYZE command.
61696 **
61697 ** @(#) $Id: analyze.c,v 1.52 2009/04/16 17:45:48 drh Exp $
61698 */
61699 #ifndef SQLITE_OMIT_ANALYZE
61700
61701 /*
61702 ** This routine generates code that opens the sqlite_stat1 table on cursor
@@ -61175,11 +61780,11 @@
61780 int endOfLoop; /* The end of the loop */
61781 int addr; /* The address of an instruction */
61782 int iDb; /* Index of database containing pTab */
61783
61784 v = sqlite3GetVdbe(pParse);
61785 if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
61786 /* Do no analysis for tables that have no indices */
61787 return;
61788 }
61789 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
61790 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
@@ -61375,17 +61980,18 @@
61980 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
61981 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
61982 return;
61983 }
61984
61985 assert( pName2!=0 || pName1==0 );
61986 if( pName1==0 ){
61987 /* Form 1: Analyze everything */
61988 for(i=0; i<db->nDb; i++){
61989 if( i==1 ) continue; /* Do not analyze the TEMP database */
61990 analyzeDatabase(pParse, i);
61991 }
61992 }else if( pName2->n==0 ){
61993 /* Form 2: Analyze the database or table named */
61994 iDb = sqlite3FindDb(db, pName1);
61995 if( iDb>=0 ){
61996 analyzeDatabase(pParse, iDb);
61997 }else{
@@ -61520,11 +62126,11 @@
62126 ** May you share freely, never taking more than you give.
62127 **
62128 *************************************************************************
62129 ** This file contains code used to implement the ATTACH and DETACH commands.
62130 **
62131 ** $Id: attach.c,v 1.90 2009/05/01 06:19:21 danielk1977 Exp $
62132 */
62133
62134 #ifndef SQLITE_OMIT_ATTACH
62135 /*
62136 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
@@ -61582,11 +62188,10 @@
62188 sqlite3 *db = sqlite3_context_db_handle(context);
62189 const char *zName;
62190 const char *zFile;
62191 Db *aNew;
62192 char *zErrDyn = 0;
 
62193
62194 UNUSED_PARAMETER(NotUsed);
62195
62196 zFile = (const char *)sqlite3_value_text(argv[0]);
62197 zName = (const char *)sqlite3_value_text(argv[1]);
@@ -61598,26 +62203,24 @@
62203 ** * Too many attached databases,
62204 ** * Transaction currently open
62205 ** * Specified database name already being used.
62206 */
62207 if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
62208 zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
 
62209 db->aLimit[SQLITE_LIMIT_ATTACHED]
62210 );
62211 goto attach_error;
62212 }
62213 if( !db->autoCommit ){
62214 zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
 
62215 goto attach_error;
62216 }
62217 for(i=0; i<db->nDb; i++){
62218 char *z = db->aDb[i].zName;
62219 assert( z && zName );
62220 if( sqlite3StrICmp(z, zName)==0 ){
62221 zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
62222 goto attach_error;
62223 }
62224 }
62225
62226 /* Allocate the new entry in the db->aDb[] array and initialise the schema
@@ -61630,29 +62233,33 @@
62233 }else{
62234 aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
62235 if( aNew==0 ) return;
62236 }
62237 db->aDb = aNew;
62238 aNew = &db->aDb[db->nDb];
62239 memset(aNew, 0, sizeof(*aNew));
62240
62241 /* Open the database file. If the btree is successfully opened, use
62242 ** it to obtain the database schema. At this point the schema may
62243 ** or may not be initialised.
62244 */
62245 rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
62246 db->openFlags | SQLITE_OPEN_MAIN_DB,
62247 &aNew->pBt);
62248 db->nDb++;
62249 if( rc==SQLITE_CONSTRAINT ){
62250 rc = SQLITE_ERROR;
62251 zErrDyn = sqlite3MPrintf(db, "database is already attached");
62252 }else if( rc==SQLITE_OK ){
62253 Pager *pPager;
62254 aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
62255 if( !aNew->pSchema ){
62256 rc = SQLITE_NOMEM;
62257 }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
62258 zErrDyn = sqlite3MPrintf(db,
62259 "attached databases must use the same text encoding as main database");
62260 rc = SQLITE_ERROR;
62261 }
62262 pPager = sqlite3BtreePager(aNew->pBt);
62263 sqlite3PagerLockingMode(pPager, db->dfltLockMode);
62264 sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
62265 }
@@ -61711,13 +62318,14 @@
62318 }
62319 sqlite3ResetInternalSchema(db, 0);
62320 db->nDb = iDb;
62321 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
62322 db->mallocFailed = 1;
62323 sqlite3DbFree(db, zErrDyn);
62324 zErrDyn = sqlite3MPrintf(db, "out of memory");
62325 }else if( zErrDyn==0 ){
62326 zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
62327 }
62328 goto attach_error;
62329 }
62330
62331 return;
@@ -61725,13 +62333,10 @@
62333 attach_error:
62334 /* Return an error if we get here */
62335 if( zErrDyn ){
62336 sqlite3_result_error(context, zErrDyn, -1);
62337 sqlite3DbFree(db, zErrDyn);
 
 
 
62338 }
62339 if( rc ) sqlite3_result_error_code(context, rc);
62340 }
62341
62342 /*
@@ -61919,11 +62524,11 @@
62524 const char *zType, /* "view", "trigger", or "index" */
62525 const Token *pName /* Name of the view, trigger, or index */
62526 ){
62527 sqlite3 *db;
62528
62529 if( NEVER(iDb<0) || iDb==1 ) return 0;
62530 db = pParse->db;
62531 assert( db->nDb>iDb );
62532 pFix->pParse = pParse;
62533 pFix->zDb = db->aDb[iDb].zName;
62534 pFix->zType = zType;
@@ -61951,11 +62556,11 @@
62556 ){
62557 int i;
62558 const char *zDb;
62559 struct SrcList_item *pItem;
62560
62561 if( NEVER(pList==0) ) return 0;
62562 zDb = pFix->zDb;
62563 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
62564 if( pItem->zDatabase==0 ){
62565 pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
62566 }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
@@ -62064,11 +62669,11 @@
62669 ** This file contains code used to implement the sqlite3_set_authorizer()
62670 ** API. This facility is an optional feature of the library. Embedded
62671 ** systems that do not need this facility may omit it by recompiling
62672 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
62673 **
62674 ** $Id: auth.c,v 1.31 2009/05/04 18:01:40 drh Exp $
62675 */
62676
62677 /*
62678 ** All of the code in this file may be omitted by defining a single
62679 ** macro.
@@ -62135,14 +62740,12 @@
62740
62741 /*
62742 ** Write an error message into pParse->zErrMsg that explains that the
62743 ** user-supplied authorization function returned an illegal value.
62744 */
62745 static void sqliteAuthBadReturnCode(Parse *pParse){
62746 sqlite3ErrorMsg(pParse, "authorizer malfunction");
 
 
62747 pParse->rc = SQLITE_ERROR;
62748 }
62749
62750 /*
62751 ** The pExpr should be a TK_COLUMN expression. The table referred to
@@ -62167,30 +62770,34 @@
62770 const char *zDBase; /* Name of database being accessed */
62771 TriggerStack *pStack; /* The stack of current triggers */
62772 int iDb; /* The index of the database the expression refers to */
62773
62774 if( db->xAuth==0 ) return;
62775 assert( pExpr->op==TK_COLUMN );
62776 iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
62777 if( iDb<0 ){
62778 /* An attempt to read a column out of a subquery or other
62779 ** temporary table. */
62780 return;
62781 }
62782 if( pTabList ){
62783 for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
62784 if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
62785 }
62786 assert( iSrc<pTabList->nSrc );
62787 pTab = pTabList->a[iSrc].pTab;
62788 }else{
62789 pStack = pParse->trigStack;
62790 if( ALWAYS(pStack) ){
62791 /* This must be an attempt to read the NEW or OLD pseudo-tables
62792 ** of a trigger.
62793 */
62794 assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
62795 pTab = pStack->pTab;
62796 }
62797 }
62798 if( NEVER(pTab==0) ) return;
62799 if( pExpr->iColumn>=0 ){
62800 assert( pExpr->iColumn<pTab->nCol );
62801 zCol = pTab->aCol[pExpr->iColumn].zName;
62802 }else if( pTab->iPKey>=0 ){
62803 assert( pTab->iPKey<pTab->nCol );
@@ -62211,11 +62818,11 @@
62818 }else{
62819 sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited",pTab->zName,zCol);
62820 }
62821 pParse->rc = SQLITE_AUTH;
62822 }else if( rc!=SQLITE_OK ){
62823 sqliteAuthBadReturnCode(pParse);
62824 }
62825 }
62826
62827 /*
62828 ** Do an authorization check using the code and arguments given. Return
@@ -62247,11 +62854,11 @@
62854 if( rc==SQLITE_DENY ){
62855 sqlite3ErrorMsg(pParse, "not authorized");
62856 pParse->rc = SQLITE_AUTH;
62857 }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
62858 rc = SQLITE_DENY;
62859 sqliteAuthBadReturnCode(pParse);
62860 }
62861 return rc;
62862 }
62863
62864 /*
@@ -62262,15 +62869,14 @@
62869 SQLITE_PRIVATE void sqlite3AuthContextPush(
62870 Parse *pParse,
62871 AuthContext *pContext,
62872 const char *zContext
62873 ){
62874 assert( pParse );
62875 pContext->pParse = pParse;
62876 pContext->zAuthContext = pParse->zAuthContext;
62877 pParse->zAuthContext = zContext;
 
 
62878 }
62879
62880 /*
62881 ** Pop an authorization context that was previously pushed
62882 ** by sqlite3AuthContextPush
@@ -62308,11 +62914,11 @@
62914 ** creating ID lists
62915 ** BEGIN TRANSACTION
62916 ** COMMIT
62917 ** ROLLBACK
62918 **
62919 ** $Id: build.c,v 1.537 2009/05/06 18:42:21 drh Exp $
62920 */
62921
62922 /*
62923 ** This routine is called when a new SQL statement is beginning to
62924 ** be parsed. Initialize the pParse structure as needed.
@@ -62443,11 +63049,13 @@
63049 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
63050 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
63051 if( (mask & pParse->cookieMask)==0 ) continue;
63052 sqlite3VdbeUsesBtree(v, iDb);
63053 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
63054 if( db->init.busy==0 ){
63055 sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
63056 }
63057 }
63058 #ifndef SQLITE_OMIT_VIRTUALTABLE
63059 {
63060 int i;
63061 for(i=0; i<pParse->nVtabLock; i++){
@@ -62473,11 +63081,11 @@
63081 if( v && pParse->nErr==0 && !db->mallocFailed ){
63082 #ifdef SQLITE_DEBUG
63083 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
63084 sqlite3VdbeTrace(v, trace);
63085 #endif
63086 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
63087 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
63088 pParse->nTab, pParse->explain);
63089 pParse->rc = SQLITE_DONE;
63090 pParse->colNamesSet = 0;
63091 }else if( pParse->rc==SQLITE_OK ){
@@ -62544,11 +63152,11 @@
63152 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
63153 Table *p = 0;
63154 int i;
63155 int nName;
63156 assert( zName!=0 );
63157 nName = sqlite3Strlen30(zName);
63158 for(i=OMIT_TEMPDB; i<db->nDb; i++){
63159 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
63160 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
63161 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
63162 if( p ) break;
@@ -62606,11 +63214,11 @@
63214 ** using the ATTACH command.
63215 */
63216 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
63217 Index *p = 0;
63218 int i;
63219 int nName = sqlite3Strlen30(zName);
63220 for(i=OMIT_TEMPDB; i<db->nDb; i++){
63221 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
63222 Schema *pSchema = db->aDb[j].pSchema;
63223 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
63224 assert( pSchema || (j==1 && !db->aDb[1].pBt) );
@@ -62642,11 +63250,11 @@
63250 static void sqlite3DeleteIndex(Index *p){
63251 Index *pOld;
63252 const char *zName = p->zName;
63253
63254 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
63255 sqlite3Strlen30(zName), 0);
63256 assert( pOld==0 || pOld==p );
63257 freeIndex(p);
63258 }
63259
63260 /*
@@ -62658,12 +63266,12 @@
63266 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
63267 Index *pIndex;
63268 int len;
63269 Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
63270
63271 len = sqlite3Strlen30(zIdxName);
63272 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
63273 if( pIndex ){
63274 if( pIndex->pTable->pIndex==pIndex ){
63275 pIndex->pTable->pIndex = pIndex->pNext;
63276 }else{
63277 Index *p;
@@ -62772,12 +63380,11 @@
63380 /*
63381 ** Remove the memory data structures associated with the given
63382 ** Table. No changes are made to disk by this routine.
63383 **
63384 ** This routine just deletes the data structure. It does not unlink
63385 ** the table data structure from the hash table. But it does destroy
 
63386 ** memory structures of the indices and foreign keys associated with
63387 ** the table.
63388 */
63389 SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
63390 Index *pIndex, *pNext;
@@ -62801,17 +63408,13 @@
63408 assert( pIndex->pSchema==pTable->pSchema );
63409 sqlite3DeleteIndex(pIndex);
63410 }
63411
63412 #ifndef SQLITE_OMIT_FOREIGN_KEY
63413 /* Delete all foreign keys associated with this table. */
 
 
63414 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
63415 pNextFKey = pFKey->pNextFrom;
 
 
63416 sqlite3DbFree(db, pFKey);
63417 }
63418 #endif
63419
63420 /* Delete the Table structure itself.
@@ -62831,54 +63434,40 @@
63434 ** Unlink the given table from the hash tables and the delete the
63435 ** table structure with all its indices and foreign keys.
63436 */
63437 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
63438 Table *p;
 
63439 Db *pDb;
63440
63441 assert( db!=0 );
63442 assert( iDb>=0 && iDb<db->nDb );
63443 assert( zTabName && zTabName[0] );
63444 pDb = &db->aDb[iDb];
63445 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
63446 sqlite3Strlen30(zTabName),0);
63447 sqlite3DeleteTable(p);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63448 db->flags |= SQLITE_InternChanges;
63449 }
63450
63451 /*
63452 ** Given a token, return a string that consists of the text of that
63453 ** token. Space to hold the returned string
63454 ** is obtained from sqliteMalloc() and must be freed by the calling
63455 ** function.
63456 **
63457 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
63458 ** surround the body of the token are removed.
63459 **
63460 ** Tokens are often just pointers into the original SQL text and so
63461 ** are not \000 terminated and are not persistent. The returned string
63462 ** is \000 terminated and is persistent.
63463 */
63464 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
63465 char *zName;
63466 if( pName ){
63467 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
63468 if( pName->quoted ) sqlite3Dequote(zName);
63469 }else{
63470 zName = 0;
63471 }
63472 return zName;
63473 }
@@ -63563,11 +64152,11 @@
64152 pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
64153 if( !initbusy && (!pColl || !pColl->xCmp) ){
64154 pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
64155 if( !pColl ){
64156 if( nName<0 ){
64157 nName = sqlite3Strlen30(zName);
64158 }
64159 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
64160 pColl = 0;
64161 }
64162 }
@@ -63968,30 +64557,18 @@
64557
64558 /* Add the table to the in-memory representation of the database.
64559 */
64560 if( db->init.busy && pParse->nErr==0 ){
64561 Table *pOld;
 
64562 Schema *pSchema = p->pSchema;
64563 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
64564 sqlite3Strlen30(p->zName),p);
64565 if( pOld ){
64566 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
64567 db->mallocFailed = 1;
64568 return;
64569 }
 
 
 
 
 
 
 
 
 
 
 
64570 pParse->pNewTable = 0;
64571 db->nTable++;
64572 db->flags |= SQLITE_InternChanges;
64573
64574 #ifndef SQLITE_OMIT_ALTERTABLE
@@ -64494,13 +65071,11 @@
65071 ** pTo table that the foreign key points to. flags contains all
65072 ** information about the conflict resolution algorithms specified
65073 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
65074 **
65075 ** An FKey structure is created and added to the table currently
65076 ** under construction in the pParse->pNewTable field.
 
 
65077 **
65078 ** The foreign key is set for IMMEDIATE processing. A subsequent call
65079 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
65080 */
65081 SQLITE_PRIVATE void sqlite3CreateForeignKey(
@@ -64537,11 +65112,11 @@
65112 "columns in the referenced table");
65113 goto fk_end;
65114 }else{
65115 nCol = pFromCol->nExpr;
65116 }
65117 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
65118 if( pToCol ){
65119 for(i=0; i<pToCol->nExpr; i++){
65120 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
65121 }
65122 }
@@ -64549,18 +65124,16 @@
65124 if( pFKey==0 ){
65125 goto fk_end;
65126 }
65127 pFKey->pFrom = p;
65128 pFKey->pNextFrom = p->pFKey;
65129 z = (char*)&pFKey->aCol[nCol];
 
 
65130 pFKey->zTo = z;
65131 memcpy(z, pTo->z, pTo->n);
65132 z[pTo->n] = 0;
65133 sqlite3Dequote(z);
65134 z += pTo->n+1;
 
65135 pFKey->nCol = nCol;
65136 if( pFromCol==0 ){
65137 pFKey->aCol[0].iFrom = p->nCol-1;
65138 }else{
65139 for(i=0; i<nCol; i++){
@@ -64673,23 +65246,29 @@
65246 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
65247 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
65248 regRecord = sqlite3GetTempReg(pParse);
65249 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
65250 if( pIndex->onError!=OE_None ){
65251 const int regRowid = regIdxKey + pIndex->nColumn;
65252 const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
65253 void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
65254
65255 /* The registers accessed by the OP_IsUnique opcode were allocated
65256 ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
65257 ** call above. Just before that function was freed they were released
65258 ** (made available to the compiler for reuse) using
65259 ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
65260 ** opcode use the values stored within seems dangerous. However, since
65261 ** we can be sure that no other temp registers have been allocated
65262 ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
65263 */
65264 sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
65265 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
65266 "indexed columns are not unique", P4_STATIC);
 
 
65267 }
65268 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
65269 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
65270 sqlite3ReleaseTempReg(pParse, regRecord);
65271 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
65272 sqlite3VdbeJumpHere(v, addr1);
65273 sqlite3VdbeAddOp1(v, OP_Close, iTab);
65274 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
@@ -64868,10 +65447,11 @@
65447 ** So create a fake list to simulate this.
65448 */
65449 if( pList==0 ){
65450 nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
65451 nullId.n = sqlite3Strlen30((char*)nullId.z);
65452 nullId.quoted = 0;
65453 pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
65454 if( pList==0 ) goto exit_create_index;
65455 pList->a[0].sortOrder = (u8)sortOrder;
65456 }
65457
@@ -65024,11 +65604,11 @@
65604 ** in-memory database structures.
65605 */
65606 if( db->init.busy ){
65607 Index *p;
65608 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
65609 pIndex->zName, sqlite3Strlen30(pIndex->zName),
65610 pIndex);
65611 if( p ){
65612 assert( p==pIndex ); /* Malloc must have failed */
65613 db->mallocFailed = 1;
65614 goto exit_create_index;
@@ -65981,11 +66561,11 @@
66561 *************************************************************************
66562 **
66563 ** This file contains functions used to access the internal hash tables
66564 ** of user defined functions and collation sequences.
66565 **
66566 ** $Id: callback.c,v 1.39 2009/05/03 20:23:53 drh Exp $
66567 */
66568
66569
66570 /*
66571 ** Invoke the 'collation needed' callback to request a collation sequence
@@ -65992,11 +66572,11 @@
66572 ** in the database text encoding of name zName, length nName.
66573 ** If the collation sequence
66574 */
66575 static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
66576 assert( !db->xCollNeeded || !db->xCollNeeded16 );
66577 if( nName<0 ) nName = sqlite3Strlen30(zName);
66578 if( db->xCollNeeded ){
66579 char *zExternal = sqlite3DbStrNDup(db, zName, nName);
66580 if( !zExternal ) return;
66581 db->xCollNeeded(db->pCollNeededArg, db, (int)ENC(db), zExternal);
66582 sqlite3DbFree(db, zExternal);
@@ -66125,11 +66705,11 @@
66705 const char *zName,
66706 int nName,
66707 int create
66708 ){
66709 CollSeq *pColl;
66710 if( nName<0 ) nName = sqlite3Strlen30(zName);
66711 pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
66712
66713 if( 0==pColl && create ){
66714 pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
66715 if( pColl ){
@@ -66380,18 +66960,17 @@
66960 HashElem *pElem;
66961 Schema *pSchema = (Schema *)p;
66962
66963 temp1 = pSchema->tblHash;
66964 temp2 = pSchema->trigHash;
66965 sqlite3HashInit(&pSchema->trigHash);
 
66966 sqlite3HashClear(&pSchema->idxHash);
66967 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
66968 sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
66969 }
66970 sqlite3HashClear(&temp2);
66971 sqlite3HashInit(&pSchema->tblHash);
66972 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
66973 Table *pTab = sqliteHashData(pElem);
66974 assert( pTab->dbMem==0 );
66975 sqlite3DeleteTable(pTab);
66976 }
@@ -66412,14 +66991,13 @@
66991 p = (Schema *)sqlite3MallocZero(sizeof(Schema));
66992 }
66993 if( !p ){
66994 db->mallocFailed = 1;
66995 }else if ( 0==p->file_format ){
66996 sqlite3HashInit(&p->tblHash);
66997 sqlite3HashInit(&p->idxHash);
66998 sqlite3HashInit(&p->trigHash);
 
66999 p->enc = SQLITE_UTF8;
67000 }
67001 return p;
67002 }
67003
@@ -66437,11 +67015,11 @@
67015 **
67016 *************************************************************************
67017 ** This file contains C code routines that are called by the parser
67018 ** in order to generate code for DELETE FROM statements.
67019 **
67020 ** $Id: delete.c,v 1.201 2009/05/01 21:13:37 drh Exp $
67021 */
67022
67023 /*
67024 ** Look up every table that is named in pSrc. If any table is not found,
67025 ** add an error message to pParse->zErrMsg and return NULL. If all tables
@@ -66486,30 +67064,10 @@
67064 }
67065 #endif
67066 return 0;
67067 }
67068
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67069
67070 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
67071 /*
67072 ** Evaluate a view and store its result in an ephemeral table. The
67073 ** pWhere argument is an optional WHERE clause that restricts the
@@ -66531,10 +67089,11 @@
67089 Token viewName;
67090
67091 pWhere = sqlite3ExprDup(db, pWhere, 0);
67092 viewName.z = (u8*)pView->zName;
67093 viewName.n = (unsigned int)sqlite3Strlen30((const char*)viewName.z);
67094 viewName.quoted = 0;
67095 pFrom = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, &viewName, pDup, 0,0);
67096 pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
67097 }
67098 sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
67099 sqlite3Select(pParse, pDup, &dest);
@@ -66801,14 +67360,12 @@
67360 ** It is easier just to erase the whole table. Note, however, that
67361 ** this means that the row change count will be incorrect.
67362 */
67363 if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) ){
67364 assert( !isView );
67365 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
67366 pTab->zName, P4_STATIC);
 
 
67367 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
67368 assert( pIdx->pSchema==pTab->pSchema );
67369 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
67370 }
67371 }else
@@ -66817,17 +67374,19 @@
67374 ** the table and pick which records to delete.
67375 */
67376 {
67377 int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
67378 int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
67379 int regRowid; /* Actual register containing rowids */
67380
67381 /* Collect rowids of every row to be deleted.
67382 */
67383 sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
67384 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
 
67385 if( pWInfo==0 ) goto delete_from_cleanup;
67386 regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
67387 sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
67388 if( db->flags & SQLITE_CountRows ){
67389 sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
67390 }
67391 sqlite3WhereEnd(pWInfo);
67392
@@ -67074,11 +67633,11 @@
67633 **
67634 ** There is only one exported symbol in this file - the function
67635 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
67636 ** All other code has file scope.
67637 **
67638 ** $Id: func.c,v 1.234 2009/04/20 12:07:37 drh Exp $
67639 */
67640
67641 /*
67642 ** Return the collating function associated with a function.
67643 */
@@ -68233,16 +68792,18 @@
68792 p = sqlite3_aggregate_context(context, sizeof(*p));
68793 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
68794 p->n++;
68795 }
68796
68797 #ifndef SQLITE_OMIT_DEPRECATED
68798 /* The sqlite3_aggregate_count() function is deprecated. But just to make
68799 ** sure it still operates correctly, verify that its count agrees with our
68800 ** internal count when using count(*) and when the total count can be
68801 ** expressed as a 32-bit integer. */
68802 assert( argc==1 || p==0 || p->n>0x7fffffff
68803 || p->n==sqlite3_aggregate_count(context) );
68804 #endif
68805 }
68806 static void countFinalize(sqlite3_context *context){
68807 CountCtx *p;
68808 p = sqlite3_aggregate_context(context, 0);
68809 sqlite3_result_int64(context, p ? p->n : 0);
@@ -68312,13 +68873,19 @@
68873 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
68874 pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
68875
68876 if( pAccum ){
68877 sqlite3 *db = sqlite3_context_db_handle(context);
68878 int n;
68879 pAccum->useMalloc = 1;
68880 pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
68881 #ifdef SQLITE_OMIT_DEPRECATED
68882 n = context->pMem->n;
68883 #else
68884 n = sqlite3_aggregate_count(context);
68885 #endif
68886 if( n>1 ){
68887 if( argc==2 ){
68888 zSep = (char*)sqlite3_value_text(argv[1]);
68889 nSep = sqlite3_value_bytes(argv[1]);
68890 }else{
68891 zSep = ",";
@@ -68539,12 +69106,32 @@
69106 **
69107 *************************************************************************
69108 ** This file contains C code routines that are called by the parser
69109 ** to handle INSERT statements in SQLite.
69110 **
69111 ** $Id: insert.c,v 1.267 2009/05/04 11:42:30 danielk1977 Exp $
69112 */
69113
69114 /*
69115 ** Generate code that will open a table for reading.
69116 */
69117 SQLITE_PRIVATE void sqlite3OpenTable(
69118 Parse *p, /* Generate code into this VDBE */
69119 int iCur, /* The cursor number of the table */
69120 int iDb, /* The database index in sqlite3.aDb[] */
69121 Table *pTab, /* The table to be opened */
69122 int opcode /* OP_OpenRead or OP_OpenWrite */
69123 ){
69124 Vdbe *v;
69125 if( IsVirtual(pTab) ) return;
69126 v = sqlite3GetVdbe(p);
69127 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
69128 sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
69129 sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
69130 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
69131 VdbeComment((v, "%s", pTab->zName));
69132 }
69133
69134 /*
69135 ** Set P4 of the most recently inserted opcode to a column affinity
69136 ** string for index pIdx. A column affinity string has one character
69137 ** for each column in the table, according to the affinity of the column:
@@ -68941,11 +69528,11 @@
69528
69529 /* Locate the table into which we will be inserting new information.
69530 */
69531 assert( pTabList->nSrc==1 );
69532 zTab = pTabList->a[0].zName;
69533 if( NEVER(zTab==0) ) goto insert_cleanup;
69534 pTab = sqlite3SrcListLookup(pParse, pTabList);
69535 if( pTab==0 ){
69536 goto insert_cleanup;
69537 }
69538 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
@@ -69063,11 +69650,12 @@
69650 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
69651 VdbeComment((v, "Jump over SELECT coroutine"));
69652
69653 /* Resolve the expressions in the SELECT statement and execute it. */
69654 rc = sqlite3Select(pParse, pSelect, &dest);
69655 assert( pParse->nErr==0 || rc );
69656 if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
69657 goto insert_cleanup;
69658 }
69659 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
69660 sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */
69661 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
@@ -69149,11 +69737,11 @@
69737 }
69738 }
69739 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
69740 sqlite3ErrorMsg(pParse,
69741 "table %S has %d columns but %d values were supplied",
69742 pTabList, 0, pTab->nCol-nHidden, nColumn);
69743 goto insert_cleanup;
69744 }
69745 if( pColumn!=0 && nColumn!=pColumn->nId ){
69746 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
69747 goto insert_cleanup;
@@ -69287,16 +69875,18 @@
69875 ** not happened yet) so we substitute a rowid of -1
69876 */
69877 regTrigRowid = sqlite3GetTempReg(pParse);
69878 if( keyColumn<0 ){
69879 sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
 
 
69880 }else{
69881 int j1;
69882 if( useTempTable ){
69883 sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regTrigRowid);
69884 }else{
69885 assert( pSelect==0 ); /* Otherwise useTempTable is true */
69886 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regTrigRowid);
69887 }
69888 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regTrigRowid);
69889 sqlite3VdbeAddOp2(v, OP_Integer, -1, regTrigRowid);
69890 sqlite3VdbeJumpHere(v, j1);
69891 sqlite3VdbeAddOp1(v, OP_MustBeInt, regTrigRowid);
69892 }
@@ -69366,11 +69956,11 @@
69956 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
69957 }else{
69958 VdbeOp *pOp;
69959 sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
69960 pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1);
69961 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
69962 appendFlag = 1;
69963 pOp->opcode = OP_NewRowid;
69964 pOp->p1 = baseCur;
69965 pOp->p2 = regRowid;
69966 pOp->p3 = regAutoinc;
@@ -69446,31 +70036,18 @@
70036 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns,
70037 (const char*)pTab->pVtab, P4_VTAB);
70038 }else
70039 #endif
70040 {
70041 int isReplace; /* Set to true if constraints may cause a replace */
70042 sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
70043 keyColumn>=0, 0, onError, endOfLoop, &isReplace
 
 
 
 
 
 
 
70044 );
70045 sqlite3CompleteInsertion(
70046 pParse, pTab, baseCur, regIns, aRegIdx, 0,
70047 (tmask&TRIGGER_AFTER) ? newIdx : -1, appendFlag, isReplace==0
70048 );
 
 
 
 
 
 
70049 }
70050 }
70051
70052 /* Update the count of rows that are inserted
70053 */
@@ -69616,22 +70193,23 @@
70193 int regRowid, /* Index of the range of input registers */
70194 int *aRegIdx, /* Register used by each index. 0 for unused indices */
70195 int rowidChng, /* True if the rowid might collide with existing entry */
70196 int isUpdate, /* True for UPDATE, False for INSERT */
70197 int overrideError, /* Override onError to this if not OE_Default */
70198 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
70199 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
70200 ){
70201 int i; /* loop counter */
70202 Vdbe *v; /* VDBE under constrution */
70203 int nCol; /* Number of columns */
70204 int onError; /* Conflict resolution strategy */
70205 int j1; /* Addresss of jump instruction */
70206 int j2 = 0, j3; /* Addresses of jump instructions */
70207 int regData; /* Register containing first data column */
70208 int iCur; /* Table cursor number */
70209 Index *pIdx; /* Pointer to one of the indices */
70210 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
70211 int hasTwoRowids = (isUpdate && rowidChng);
70212
70213 v = sqlite3GetVdbe(pParse);
70214 assert( v!=0 );
70215 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
@@ -69671,11 +70249,12 @@
70249 }
70250 case OE_Ignore: {
70251 sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
70252 break;
70253 }
70254 default: {
70255 assert( onError==OE_Replace );
70256 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
70257 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
70258 sqlite3VdbeJumpHere(v, j1);
70259 break;
70260 }
@@ -69768,15 +70347,17 @@
70347 }
70348 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
70349 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
70350 sqlite3IndexAffinityStr(v, pIdx);
70351 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
 
70352
70353 /* Find out what action to take in case there is an indexing conflict */
70354 onError = pIdx->onError;
70355 if( onError==OE_None ){
70356 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
70357 continue; /* pIdx is not a UNIQUE index */
70358 }
70359 if( overrideError!=OE_Default ){
70360 onError = overrideError;
70361 }else if( onError==OE_Default ){
70362 onError = OE_Abort;
70363 }
@@ -69785,65 +70366,64 @@
70366 else if( onError==OE_Fail ) onError = OE_Abort;
70367 }
70368
70369
70370 /* Check to see if the new index entry will be unique */
 
70371 regR = sqlite3GetTempReg(pParse);
70372 sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR);
70373 j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
70374 regR, SQLITE_INT_TO_PTR(regIdx),
70375 P4_INT32);
70376 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
70377
70378 /* Generate code that executes if the new index entry is not unique */
70379 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
70380 || onError==OE_Ignore || onError==OE_Replace );
70381 switch( onError ){
70382 case OE_Rollback:
70383 case OE_Abort:
70384 case OE_Fail: {
70385 int j;
70386 StrAccum errMsg;
70387 const char *zSep;
70388 char *zErr;
70389
70390 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
70391 errMsg.db = pParse->db;
70392 zSep = pIdx->nColumn>1 ? "columns " : "column ";
70393 for(j=0; j<pIdx->nColumn; j++){
70394 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
70395 sqlite3StrAccumAppend(&errMsg, zSep, -1);
70396 zSep = ", ";
70397 sqlite3StrAccumAppend(&errMsg, zCol, -1);
70398 }
70399 sqlite3StrAccumAppend(&errMsg,
70400 pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
70401 zErr = sqlite3StrAccumFinish(&errMsg);
70402 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErr, 0);
70403 sqlite3DbFree(errMsg.db, zErr);
 
 
 
 
 
 
 
 
70404 break;
70405 }
70406 case OE_Ignore: {
70407 assert( seenReplace==0 );
70408 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
70409 break;
70410 }
70411 default: {
70412 assert( onError==OE_Replace );
70413 sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0);
70414 seenReplace = 1;
70415 break;
70416 }
70417 }
 
70418 sqlite3VdbeJumpHere(v, j3);
70419 sqlite3ReleaseTempReg(pParse, regR);
70420 }
70421
70422 if( pbMayReplace ){
70423 *pbMayReplace = seenReplace;
70424 }
70425 }
70426
70427 /*
70428 ** This routine generates code to finish the INSERT or UPDATE operation
70429 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
@@ -69859,11 +70439,12 @@
70439 int baseCur, /* Index of a read/write cursor pointing at pTab */
70440 int regRowid, /* Range of content */
70441 int *aRegIdx, /* Register used by each index. 0 for unused indices */
70442 int isUpdate, /* True for UPDATE, False for INSERT */
70443 int newIdx, /* Index of NEW table for triggers. -1 if none */
70444 int appendBias, /* True if this is likely to be an append */
70445 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
70446 ){
70447 int i;
70448 Vdbe *v;
70449 int nIdx;
70450 Index *pIdx;
@@ -69876,10 +70457,13 @@
70457 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
70458 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
70459 for(i=nIdx-1; i>=0; i--){
70460 if( aRegIdx[i]==0 ) continue;
70461 sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
70462 if( useSeekResult ){
70463 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
70464 }
70465 }
70466 regData = regRowid + 1;
70467 regRec = sqlite3GetTempReg(pParse);
70468 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
70469 sqlite3TableAffinityStr(v, pTab);
@@ -69896,10 +70480,13 @@
70480 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
70481 }
70482 if( appendBias ){
70483 pik_flags |= OPFLAG_APPEND;
70484 }
70485 if( useSeekResult ){
70486 pik_flags |= OPFLAG_USESEEKRESULT;
70487 }
70488 sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
70489 if( !pParse->nested ){
70490 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
70491 }
70492 sqlite3VdbeChangeP5(v, pik_flags);
@@ -69933,11 +70520,11 @@
70520 assert( pIdx->pSchema==pTab->pSchema );
70521 sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
70522 (char*)pKey, P4_KEYINFO_HANDOFF);
70523 VdbeComment((v, "%s", pIdx->zName));
70524 }
70525 if( pParse->nTab<baseCur+i ){
70526 pParse->nTab = baseCur+i;
70527 }
70528 return i-1;
70529 }
70530
@@ -69993,11 +70580,11 @@
70580 return 0; /* Different columns indexed */
70581 }
70582 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
70583 return 0; /* Different sort orders */
70584 }
70585 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
70586 return 0; /* Different collating sequences */
70587 }
70588 }
70589
70590 /* If no test above fails then the indices must be compatible */
@@ -70224,11 +70811,11 @@
70811 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
70812 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
70813 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
70814 autoIncEnd(pParse, iDbDest, pDest, regAutoinc);
70815 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
70816 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
70817 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
70818 }
70819 assert( pSrcIdx );
70820 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
70821 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
@@ -70283,11 +70870,11 @@
70870 ** Main file for the SQLite library. The routines in this file
70871 ** implement the programmer interface to the library. Routines in
70872 ** other files are for internal use by SQLite and should not be
70873 ** accessed by users of the library.
70874 **
70875 ** $Id: legacy.c,v 1.33 2009/05/05 20:02:48 drh Exp $
70876 */
70877
70878
70879 /*
70880 ** Execute SQL code. Return one of the SQLITE_ success/failure
@@ -70304,17 +70891,16 @@
70891 const char *zSql, /* The SQL to be executed */
70892 sqlite3_callback xCallback, /* Invoke this callback routine */
70893 void *pArg, /* First argument to xCallback() */
70894 char **pzErrMsg /* Write error messages here */
70895 ){
70896 int rc = SQLITE_OK; /* Return code */
70897 const char *zLeftover; /* Tail of unprocessed SQL */
70898 sqlite3_stmt *pStmt = 0; /* The current SQL statement */
70899 char **azCols = 0; /* Names of result columns */
70900 int nRetry = 0; /* Number of retry attempts */
70901 int callbackIsInit; /* True if callback data is initialized */
 
70902
70903 if( zSql==0 ) zSql = "";
70904
70905 sqlite3_mutex_enter(db->mutex);
70906 sqlite3Error(db, SQLITE_OK, 0);
@@ -70332,34 +70918,33 @@
70918 /* this happens for a comment or white-space */
70919 zSql = zLeftover;
70920 continue;
70921 }
70922
70923 callbackIsInit = 0;
70924 nCol = sqlite3_column_count(pStmt);
70925
70926 while( 1 ){
70927 int i;
70928 rc = sqlite3_step(pStmt);
70929
70930 /* Invoke the callback function if required */
70931 if( xCallback && (SQLITE_ROW==rc ||
70932 (SQLITE_DONE==rc && !callbackIsInit
70933 && db->flags&SQLITE_NullCallback)) ){
70934 if( !callbackIsInit ){
70935 azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
70936 if( azCols==0 ){
70937 goto exec_out;
 
 
 
70938 }
70939 for(i=0; i<nCol; i++){
70940 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
70941 /* sqlite3VdbeSetColName() installs column names as UTF8
70942 ** strings so there is no way for sqlite3_column_name() to fail. */
70943 assert( azCols[i]!=0 );
70944 }
70945 callbackIsInit = 1;
70946 }
70947 if( rc==SQLITE_ROW ){
70948 azVals = &azCols[nCol];
70949 for(i=0; i<nCol; i++){
70950 azVals[i] = (char *)sqlite3_column_text(pStmt, i);
@@ -70397,11 +70982,11 @@
70982 exec_out:
70983 if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
70984 sqlite3DbFree(db, azCols);
70985
70986 rc = sqlite3ApiExit(db, rc);
70987 if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
70988 int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
70989 *pzErrMsg = sqlite3Malloc(nErrMsg);
70990 if( *pzErrMsg ){
70991 memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
70992 }
@@ -72848,11 +73433,11 @@
73433 *************************************************************************
73434 ** This file contains the implementation of the sqlite3_prepare()
73435 ** interface, and routines that contribute to loading the database schema
73436 ** from disk.
73437 **
73438 ** $Id: prepare.c,v 1.117 2009/04/20 17:43:03 drh Exp $
73439 */
73440
73441 /*
73442 ** Fill the InitData structure with an error message that indicates
73443 ** that the database is corrupt.
@@ -72961,10 +73546,11 @@
73546 ** auxiliary databases. Return one of the SQLITE_ error codes to
73547 ** indicate success or failure.
73548 */
73549 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
73550 int rc;
73551 int i;
73552 BtCursor *curMain;
73553 int size;
73554 Table *pTab;
73555 Db *pDb;
73556 char const *azArg[4];
@@ -73050,11 +73636,12 @@
73636 rc = SQLITE_NOMEM;
73637 goto error_out;
73638 }
73639 sqlite3BtreeEnter(pDb->pBt);
73640 rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, curMain);
73641 if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
73642 if( rc!=SQLITE_OK ){
73643 sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
73644 goto initone_error_out;
73645 }
73646
73647 /* Get the database meta information.
@@ -73072,21 +73659,16 @@
73659 ** meta[9]
73660 **
73661 ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
73662 ** the possible values of meta[4].
73663 */
73664 for(i=0; i<ArraySize(meta); i++){
73665 rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
73666 if( rc ){
73667 sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
73668 goto initone_error_out;
73669 }
 
 
 
 
 
73670 }
73671 pDb->pSchema->schema_cookie = meta[0];
73672
73673 /* If opening a non-empty database, check the text encoding. For the
73674 ** main database, set sqlite3.enc to the encoding of the main database.
@@ -73683,11 +74265,11 @@
74265 **
74266 *************************************************************************
74267 ** This file contains C code routines that are called by the parser
74268 ** to handle SELECT statements in SQLite.
74269 **
74270 ** $Id: select.c,v 1.512 2009/05/03 20:23:54 drh Exp $
74271 */
74272
74273
74274 /*
74275 ** Delete all the content of a Select structure but do not deallocate
@@ -73863,46 +74445,11 @@
74445 */
74446 static void setToken(Token *p, const char *z){
74447 p->z = (u8*)z;
74448 p->n = z ? sqlite3Strlen30(z) : 0;
74449 p->dyn = 0;
74450 p->quoted = 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74451 }
74452
74453 /*
74454 ** Create an expression node for an identifier with the name of zName
74455 */
@@ -74091,10 +74638,11 @@
74638 ){
74639 Vdbe *v = pParse->pVdbe;
74640 int nExpr = pOrderBy->nExpr;
74641 int regBase = sqlite3GetTempRange(pParse, nExpr+2);
74642 int regRecord = sqlite3GetTempReg(pParse);
74643 sqlite3ExprCacheClear(pParse);
74644 sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
74645 sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
74646 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
74647 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
74648 sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
@@ -74243,10 +74791,11 @@
74791 }
74792 }else if( eDest!=SRT_Exists ){
74793 /* If the destination is an EXISTS(...) expression, the actual
74794 ** values returned by the SELECT are not required.
74795 */
74796 sqlite3ExprCacheClear(pParse);
74797 sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
74798 }
74799 nColumn = nResultCol;
74800
74801 /* If the DISTINCT keyword was present on the SELECT statement
@@ -74860,11 +75409,10 @@
75409 }
75410 if( db->mallocFailed ){
75411 sqlite3DbFree(db, zName);
75412 break;
75413 }
 
75414
75415 /* Make sure the column name is unique. If the name is not unique,
75416 ** append a integer to the name so that it becomes unique.
75417 */
75418 nName = sqlite3Strlen30(zName);
@@ -75016,10 +75564,11 @@
75564 ** "LIMIT -1" always shows all rows. There is some
75565 ** contraversy about what the correct behavior should be.
75566 ** The current implementation interprets "LIMIT 0" to mean
75567 ** no rows.
75568 */
75569 sqlite3ExprCacheClear(pParse);
75570 if( p->pLimit ){
75571 p->iLimit = iLimit = ++pParse->nMem;
75572 v = sqlite3GetVdbe(pParse);
75573 if( v==0 ) return;
75574 sqlite3ExprCode(pParse, p->pLimit, iLimit);
@@ -75064,11 +75613,12 @@
75613 if( p->pPrior ){
75614 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
75615 }else{
75616 pRet = 0;
75617 }
75618 assert( iCol>=0 );
75619 if( pRet==0 && iCol<p->pEList->nExpr ){
75620 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
75621 }
75622 return pRet;
75623 }
75624 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
@@ -75771,11 +76321,11 @@
76321 }
76322 }
76323 }
76324
76325 /* Compute the comparison permutation and keyinfo that is used with
76326 ** the permutation used to determine if the next
76327 ** row of results comes from selectA or selectB. Also add explicit
76328 ** collations to the ORDER BY clause terms so that when the subqueries
76329 ** to the right and the left are evaluated, they use the correct
76330 ** collation.
76331 */
@@ -76894,16 +77444,16 @@
77444 continue;
77445 }
77446 }
77447 pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
77448 if( pRight==0 ) break;
77449 setToken(&pRight->token, zName);
77450 if( longNames || pTabList->nSrc>1 ){
77451 Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
77452 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
77453 if( pExpr==0 ) break;
77454 setToken(&pLeft->token, zTabName);
77455 setToken(&pExpr->span,
77456 sqlite3MPrintf(db, "%s.%s", zTabName, zName));
77457 pExpr->span.dyn = 1;
77458 pExpr->token.z = 0;
77459 pExpr->token.n = 0;
@@ -77125,10 +77675,11 @@
77675 int i;
77676 struct AggInfo_func *pF;
77677 struct AggInfo_col *pC;
77678
77679 pAggInfo->directMode = 1;
77680 sqlite3ExprCacheClear(pParse);
77681 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
77682 int nArg;
77683 int addrNext = 0;
77684 int regAgg;
77685 ExprList *pList = pF->pExpr->x.pList;
@@ -77164,16 +77715,18 @@
77715 sqlite3VdbeChangeP5(v, (u8)nArg);
77716 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
77717 sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
77718 if( addrNext ){
77719 sqlite3VdbeResolveLabel(v, addrNext);
77720 sqlite3ExprCacheClear(pParse);
77721 }
77722 }
77723 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
77724 sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
77725 }
77726 pAggInfo->directMode = 0;
77727 sqlite3ExprCacheClear(pParse);
77728 }
77729
77730 /*
77731 ** Generate code for the SELECT statement given in the p argument.
77732 **
@@ -77434,11 +77987,11 @@
77987 /* Aggregate and non-aggregate queries are handled differently */
77988 if( !isAgg && pGroupBy==0 ){
77989 /* This case is for non-aggregate queries
77990 ** Begin the database scan
77991 */
77992 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
77993 if( pWInfo==0 ) goto select_end;
77994
77995 /* If sorting index that was created by a prior OP_OpenEphemeral
77996 ** instruction ended up not being needed, then change the OP_OpenEphemeral
77997 ** into an OP_Noop.
@@ -77556,11 +78109,11 @@
78109 ** This might involve two separate loops with an OP_Sort in between, or
78110 ** it might be a single loop that uses an index to extract information
78111 ** in the right order to begin with.
78112 */
78113 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
78114 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
78115 if( pWInfo==0 ) goto select_end;
78116 if( pGroupBy==0 ){
78117 /* The optimizer is able to deliver rows in group by order so
78118 ** we do not have to sort. The OP_OpenEphemeral table will be
78119 ** cancelled later because we still need to use the pKeyInfo
@@ -77587,10 +78140,11 @@
78140 nCol++;
78141 j++;
78142 }
78143 }
78144 regBase = sqlite3GetTempRange(pParse, nCol);
78145 sqlite3ExprCacheClear(pParse);
78146 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
78147 sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
78148 j = nGroupBy+1;
78149 for(i=0; i<sAggInfo.nColumn; i++){
78150 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
@@ -77613,18 +78167,20 @@
78167 sqlite3ReleaseTempRange(pParse, regBase, nCol);
78168 sqlite3WhereEnd(pWInfo);
78169 sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
78170 VdbeComment((v, "GROUP BY sort"));
78171 sAggInfo.useSortingIdx = 1;
78172 sqlite3ExprCacheClear(pParse);
78173 }
78174
78175 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
78176 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
78177 ** Then compare the current GROUP BY terms against the GROUP BY terms
78178 ** from the previous row currently stored in a0, a1, a2...
78179 */
78180 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
78181 sqlite3ExprCacheClear(pParse);
78182 for(j=0; j<pGroupBy->nExpr; j++){
78183 if( groupBySort ){
78184 sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
78185 }else{
78186 sAggInfo.directMode = 1;
@@ -77811,11 +78367,11 @@
78367 /* This case runs if the aggregate has no GROUP BY clause. The
78368 ** processing is much simpler since there is only a single row
78369 ** of output.
78370 */
78371 resetAccumulator(pParse, &sAggInfo);
78372 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
78373 if( pWInfo==0 ){
78374 sqlite3ExprListDelete(db, pDel);
78375 goto select_end;
78376 }
78377 updateAccumulator(pParse, &sAggInfo);
@@ -78179,11 +78735,11 @@
78735 ** May you share freely, never taking more than you give.
78736 **
78737 *************************************************************************
78738 **
78739 **
78740 ** $Id: trigger.c,v 1.138 2009/05/06 18:42:21 drh Exp $
78741 */
78742
78743 #ifndef SQLITE_OMIT_TRIGGER
78744 /*
78745 ** Delete a linked list of TriggerStep structures.
@@ -78453,11 +79009,11 @@
79009 pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
79010 if( pTrig ){
79011 db->mallocFailed = 1;
79012 }else if( pLink->pSchema==pLink->pTabSchema ){
79013 Table *pTab;
79014 int n = sqlite3Strlen30(pLink->table);
79015 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
79016 assert( pTab!=0 );
79017 pLink->pNext = pTab->pTrigger;
79018 pTab->pTrigger = pLink;
79019 }
@@ -78680,11 +79236,11 @@
79236 /*
79237 ** Return a pointer to the Table structure for the table that a trigger
79238 ** is set on.
79239 */
79240 static Table *tableOfTrigger(Trigger *pTrigger){
79241 int n = sqlite3Strlen30(pTrigger->table);
79242 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
79243 }
79244
79245
79246 /*
@@ -78831,10 +79387,11 @@
79387 iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
79388 if( iDb==0 || iDb>=2 ){
79389 assert( iDb<pParse->db->nDb );
79390 sDb.z = (u8*)pParse->db->aDb[iDb].zName;
79391 sDb.n = sqlite3Strlen30((char*)sDb.z);
79392 sDb.quoted = 0;
79393 pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target);
79394 } else {
79395 pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
79396 }
79397 return pSrc;
@@ -78857,11 +79414,11 @@
79414 assert( pTriggerStep!=0 );
79415 assert( v!=0 );
79416 sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0);
79417 VdbeComment((v, "begin trigger %s", pStepList->pTrig->name));
79418 while( pTriggerStep ){
79419 sqlite3ExprCacheClear(pParse);
79420 orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
79421 pParse->trigStack->orconf = orconf;
79422 switch( pTriggerStep->op ){
79423 case TK_SELECT: {
79424 Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect, 0);
@@ -79056,11 +79613,11 @@
79613 **
79614 *************************************************************************
79615 ** This file contains C code routines that are called by the parser
79616 ** to handle UPDATE statements.
79617 **
79618 ** $Id: update.c,v 1.200 2009/05/05 15:46:10 drh Exp $
79619 */
79620
79621 #ifndef SQLITE_OMIT_VIRTUALTABLE
79622 /* Forward declaration */
79623 static void updateVirtualTable(
@@ -79098,11 +79655,12 @@
79655 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
79656 ** function is capable of transforming these types of expressions into
79657 ** sqlite3_value objects.
79658 */
79659 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
79660 assert( pTab!=0 );
79661 if( !pTab->pSelect ){
79662 sqlite3_value *pValue;
79663 u8 enc = ENC(sqlite3VdbeDb(v));
79664 Column *pCol = &pTab->aCol[i];
79665 VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
79666 assert( i<pTab->nCol );
@@ -79388,18 +79946,17 @@
79946 }
79947
79948 /* Begin the database scan
79949 */
79950 sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
79951 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
 
79952 if( pWInfo==0 ) goto update_cleanup;
79953 okOnePass = pWInfo->okOnePass;
79954
79955 /* Remember the rowid of every item to be updated.
79956 */
79957 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
79958 if( !okOnePass ){
79959 regRowSet = ++pParse->nMem;
79960 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
79961 }
79962
@@ -79412,11 +79969,11 @@
79969 if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
79970 regRowCount = ++pParse->nMem;
79971 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
79972 }
79973
79974 if( !isView ){
79975 /*
79976 ** Open every index that needs updating. Note that if any
79977 ** index could potentially invoke a REPLACE conflict resolution
79978 ** action, then we need to open all indices because we might need
79979 ** to be deleting some records.
@@ -79491,11 +80048,11 @@
80048 if( i==pTab->iPKey ){
80049 sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i);
80050 continue;
80051 }
80052 j = aXRef[i];
80053 if( (i<32 && (new_col_mask&((u32)1<<i))!=0) || new_col_mask==0xffffffff ){
80054 if( j<0 ){
80055 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regCols+i);
80056 sqlite3ColumnDefault(v, pTab, i);
80057 }else{
80058 sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr, regCols+i);
@@ -79517,11 +80074,11 @@
80074
80075 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger);
80076 sqlite3VdbeJumpHere(v, iEndBeforeTrigger);
80077 }
80078
80079 if( !isView ){
80080 /* Loop over every record that needs updating. We have to load
80081 ** the old data for each record to be updated because some columns
80082 ** might not change and we will need to copy the old value.
80083 ** Also, the old data is needed to delete the old index entries.
80084 ** So make the cursor point at the old record.
@@ -79555,11 +80112,11 @@
80112
80113 /* Do constraint checks
80114 */
80115 sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
80116 aRegIdx, chngRowid, 1,
80117 onError, addr, 0);
80118
80119 /* Delete the old indices for the current record.
80120 */
80121 j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
80122 sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
@@ -79572,11 +80129,11 @@
80129 sqlite3VdbeJumpHere(v, j1);
80130
80131 /* Create the new index entries and the new record.
80132 */
80133 sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid,
80134 aRegIdx, 1, -1, 0, 0);
80135 }
80136
80137 /* Increment the row counter
80138 */
80139 if( db->flags & SQLITE_CountRows && !pParse->trigStack){
@@ -79745,26 +80302,28 @@
80302 ** This file contains code used to implement the VACUUM command.
80303 **
80304 ** Most of the code in this file may be omitted by defining the
80305 ** SQLITE_OMIT_VACUUM macro.
80306 **
80307 ** $Id: vacuum.c,v 1.88 2009/05/05 17:37:23 drh Exp $
80308 */
80309
80310 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
80311 /*
80312 ** Execute zSql on database db. Return an error code.
80313 */
80314 static int execSql(sqlite3 *db, const char *zSql){
80315 sqlite3_stmt *pStmt;
80316 VVA_ONLY( int rc; )
80317 if( !zSql ){
80318 return SQLITE_NOMEM;
80319 }
80320 if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
80321 return sqlite3_errcode(db);
80322 }
80323 VVA_ONLY( rc = ) sqlite3_step(pStmt);
80324 assert( rc!=SQLITE_ROW );
80325 return sqlite3_finalize(pStmt);
80326 }
80327
80328 /*
80329 ** Execute zSql on database db. The statement returns exactly
@@ -79871,11 +80430,11 @@
80430 }
80431 #endif
80432
80433 if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
80434 || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
80435 || NEVER(db->mallocFailed)
80436 ){
80437 rc = SQLITE_NOMEM;
80438 goto end_of_vacuum;
80439 }
80440 rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
@@ -79959,11 +80518,11 @@
80518 ** call to sqlite3BtreeCopyFile(). The main database btree level
80519 ** transaction is then committed, so the SQL level never knows it was
80520 ** opened for writing. This way, the SQL transaction used to create the
80521 ** temporary database never needs to be committed.
80522 */
80523 {
80524 u32 meta;
80525 int i;
80526
80527 /* This array determines which meta meta values are preserved in the
80528 ** vacuum. Even entries are the meta value number and odd entries
@@ -79981,14 +80540,16 @@
80540 assert( 1==sqlite3BtreeIsInTrans(pTemp) );
80541 assert( 1==sqlite3BtreeIsInTrans(pMain) );
80542
80543 /* Copy Btree meta values */
80544 for(i=0; i<ArraySize(aCopy); i+=2){
80545 /* GetMeta() and UpdateMeta() cannot fail in this context because
80546 ** we already have page 1 loaded into cache and marked dirty. */
80547 rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
80548 if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
80549 rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
80550 if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
80551 }
80552
80553 rc = sqlite3BtreeCopyFile(pMain, pTemp);
80554 if( rc!=SQLITE_OK ) goto end_of_vacuum;
80555 rc = sqlite3BtreeCommit(pTemp);
@@ -79996,13 +80557,12 @@
80557 #ifndef SQLITE_OMIT_AUTOVACUUM
80558 sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
80559 #endif
80560 }
80561
80562 assert( rc==SQLITE_OK );
80563 rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
 
80564
80565 end_of_vacuum:
80566 /* Restore the original value of db->flags */
80567 db->flags = saved_flags;
80568 db->nChange = saved_nChange;
@@ -80042,11 +80602,11 @@
80602 ** May you share freely, never taking more than you give.
80603 **
80604 *************************************************************************
80605 ** This file contains code used to help implement virtual tables.
80606 **
80607 ** $Id: vtab.c,v 1.86 2009/04/28 13:01:09 drh Exp $
80608 */
80609 #ifndef SQLITE_OMIT_VIRTUALTABLE
80610
80611 /*
80612 ** The actual function that does the work of creating a new module.
@@ -80338,11 +80898,11 @@
80898 */
80899 else {
80900 Table *pOld;
80901 Schema *pSchema = pTab->pSchema;
80902 const char *zName = pTab->zName;
80903 int nName = sqlite3Strlen30(zName);
80904 pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
80905 if( pOld ){
80906 db->mallocFailed = 1;
80907 assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
80908 return;
@@ -80901,11 +81461,11 @@
81461 ** generating the code that loops through a table looking for applicable
81462 ** rows. Indices are selected and used to speed the search when doing
81463 ** so is applicable. Because this module is responsible for selecting
81464 ** indices, you might also think of this module as the "query optimizer".
81465 **
81466 ** $Id: where.c,v 1.396 2009/05/06 19:03:14 drh Exp $
81467 */
81468
81469 /*
81470 ** Trace output macros
81471 */
@@ -80927,14 +81487,12 @@
81487 typedef struct WhereCost WhereCost;
81488
81489 /*
81490 ** The query generator uses an array of instances of this structure to
81491 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
81492 ** clause subexpression is separated from the others by AND operators,
81493 ** usually, or sometimes subexpressions separated by OR.
 
 
81494 **
81495 ** All WhereTerms are collected into a single WhereClause structure.
81496 ** The following identity holds:
81497 **
81498 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
@@ -81112,15 +81670,16 @@
81670 ** ISNULL constraints will then not be used on the right table of a left
81671 ** join. Tickets #2177 and #2189.
81672 */
81673 #define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
81674 #define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
81675 #define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */
81676 #define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
81677 #define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
81678 #define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */
81679 #define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */
81680 #define WHERE_IN_ABLE 0x000f1000 /* Able to support an IN operator */
81681 #define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
81682 #define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
81683 #define WHERE_IDX_ONLY 0x00800000 /* Use index only - omit table */
81684 #define WHERE_ORDERBY 0x01000000 /* Output will appear in correct order */
81685 #define WHERE_REVERSE 0x02000000 /* Scan in reverse order */
@@ -81259,20 +81818,21 @@
81818 whereSplit(pWC, pExpr->pRight, op);
81819 }
81820 }
81821
81822 /*
81823 ** Initialize an expression mask set (a WhereMaskSet object)
81824 */
81825 #define initMaskSet(P) memset(P, 0, sizeof(*P))
81826
81827 /*
81828 ** Return the bitmask for the given cursor number. Return 0 if
81829 ** iCursor is not in the set.
81830 */
81831 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
81832 int i;
81833 assert( pMaskSet->n<=sizeof(Bitmask)*8 );
81834 for(i=0; i<pMaskSet->n; i++){
81835 if( pMaskSet->ix[i]==iCursor ){
81836 return ((Bitmask)1)<<i;
81837 }
81838 }
@@ -81510,10 +82070,11 @@
82070 ){
82071 const char *z; /* String on RHS of LIKE operator */
82072 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
82073 ExprList *pList; /* List of operands to the LIKE operator */
82074 int c; /* One character in z[] */
82075 int n; /* Length of string z[] */
82076 int cnt; /* Number of non-wildcard prefix characters */
82077 char wc[3]; /* Wildcard characters */
82078 CollSeq *pColl; /* Collating sequence for LHS */
82079 sqlite3 *db = pParse->db; /* Database connection */
82080
@@ -81540,15 +82101,17 @@
82101 }
82102 if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
82103 (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
82104 return 0;
82105 }
82106 z = (const char*)pRight->token.z;
 
82107 cnt = 0;
82108 if( z ){
82109 n = pRight->token.n;
82110 while( cnt<n && (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
82111 cnt++;
82112 }
82113 }
82114 if( cnt==0 || 255==(u8)z[cnt-1] ){
82115 return 0;
82116 }
82117 *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
@@ -82045,11 +82608,10 @@
82608 pRight = pExpr->x.pList->a[0].pExpr;
82609 pStr1 = sqlite3PExpr(pParse, TK_STRING, 0, 0, 0);
82610 if( pStr1 ){
82611 sqlite3TokenCopy(db, &pStr1->token, &pRight->token);
82612 pStr1->token.n = nPattern;
 
82613 }
82614 pStr2 = sqlite3ExprDup(db, pStr1, 0);
82615 if( !db->mallocFailed ){
82616 u8 c, *pC;
82617 /* assert( pStr2->token.dyn ); */
@@ -82358,12 +82920,251 @@
82920 }
82921 #else
82922 #define TRACE_IDX_INPUTS(A)
82923 #define TRACE_IDX_OUTPUTS(A)
82924 #endif
82925
82926 /*
82927 ** Required because bestIndex() is called by bestOrClauseIndex()
82928 */
82929 static void bestIndex(
82930 Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);
82931
82932 /*
82933 ** This routine attempts to find an scanning strategy that can be used
82934 ** to optimize an 'OR' expression that is part of a WHERE clause.
82935 **
82936 ** The table associated with FROM clause term pSrc may be either a
82937 ** regular B-Tree table or a virtual table.
82938 */
82939 static void bestOrClauseIndex(
82940 Parse *pParse, /* The parsing context */
82941 WhereClause *pWC, /* The WHERE clause */
82942 struct SrcList_item *pSrc, /* The FROM clause term to search */
82943 Bitmask notReady, /* Mask of cursors that are not available */
82944 ExprList *pOrderBy, /* The ORDER BY clause */
82945 WhereCost *pCost /* Lowest cost query plan */
82946 ){
82947 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
82948 const int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
82949 const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur); /* Bitmask for pSrc */
82950 WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm]; /* End of pWC->a[] */
82951 WhereTerm *pTerm; /* A single term of the WHERE clause */
82952
82953 /* Search the WHERE clause terms for a usable WO_OR term. */
82954 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
82955 if( pTerm->eOperator==WO_OR
82956 && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
82957 && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
82958 ){
82959 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
82960 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
82961 WhereTerm *pOrTerm;
82962 int flags = WHERE_MULTI_OR;
82963 double rTotal = 0;
82964 double nRow = 0;
82965
82966 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
82967 WhereCost sTermCost;
82968 WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
82969 (pOrTerm - pOrWC->a), (pTerm - pWC->a)
82970 ));
82971 if( pOrTerm->eOperator==WO_AND ){
82972 WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
82973 bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
82974 }else if( pOrTerm->leftCursor==iCur ){
82975 WhereClause tempWC;
82976 tempWC.pParse = pWC->pParse;
82977 tempWC.pMaskSet = pWC->pMaskSet;
82978 tempWC.op = TK_AND;
82979 tempWC.a = pOrTerm;
82980 tempWC.nTerm = 1;
82981 bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
82982 }else{
82983 continue;
82984 }
82985 rTotal += sTermCost.rCost;
82986 nRow += sTermCost.nRow;
82987 if( rTotal>=pCost->rCost ) break;
82988 }
82989
82990 /* If there is an ORDER BY clause, increase the scan cost to account
82991 ** for the cost of the sort. */
82992 if( pOrderBy!=0 ){
82993 rTotal += nRow*estLog(nRow);
82994 WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
82995 }
82996
82997 /* If the cost of scanning using this OR term for optimization is
82998 ** less than the current cost stored in pCost, replace the contents
82999 ** of pCost. */
83000 WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
83001 if( rTotal<pCost->rCost ){
83002 pCost->rCost = rTotal;
83003 pCost->nRow = nRow;
83004 pCost->plan.wsFlags = flags;
83005 pCost->plan.u.pTerm = pTerm;
83006 }
83007 }
83008 }
83009 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
83010 }
83011
83012 #ifndef SQLITE_OMIT_VIRTUALTABLE
83013 /*
83014 ** Allocate and populate an sqlite3_index_info structure. It is the
83015 ** responsibility of the caller to eventually release the structure
83016 ** by passing the pointer returned by this function to sqlite3_free().
83017 */
83018 static sqlite3_index_info *allocateIndexInfo(
83019 Parse *pParse,
83020 WhereClause *pWC,
83021 struct SrcList_item *pSrc,
83022 ExprList *pOrderBy
83023 ){
83024 int i, j;
83025 int nTerm;
83026 struct sqlite3_index_constraint *pIdxCons;
83027 struct sqlite3_index_orderby *pIdxOrderBy;
83028 struct sqlite3_index_constraint_usage *pUsage;
83029 WhereTerm *pTerm;
83030 int nOrderBy;
83031 sqlite3_index_info *pIdxInfo;
83032
83033 WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
83034
83035 /* Count the number of possible WHERE clause constraints referring
83036 ** to this virtual table */
83037 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
83038 if( pTerm->leftCursor != pSrc->iCursor ) continue;
83039 assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
83040 testcase( pTerm->eOperator==WO_IN );
83041 testcase( pTerm->eOperator==WO_ISNULL );
83042 if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
83043 nTerm++;
83044 }
83045
83046 /* If the ORDER BY clause contains only columns in the current
83047 ** virtual table then allocate space for the aOrderBy part of
83048 ** the sqlite3_index_info structure.
83049 */
83050 nOrderBy = 0;
83051 if( pOrderBy ){
83052 for(i=0; i<pOrderBy->nExpr; i++){
83053 Expr *pExpr = pOrderBy->a[i].pExpr;
83054 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
83055 }
83056 if( i==pOrderBy->nExpr ){
83057 nOrderBy = pOrderBy->nExpr;
83058 }
83059 }
83060
83061 /* Allocate the sqlite3_index_info structure
83062 */
83063 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
83064 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
83065 + sizeof(*pIdxOrderBy)*nOrderBy );
83066 if( pIdxInfo==0 ){
83067 sqlite3ErrorMsg(pParse, "out of memory");
83068 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
83069 return 0;
83070 }
83071
83072 /* Initialize the structure. The sqlite3_index_info structure contains
83073 ** many fields that are declared "const" to prevent xBestIndex from
83074 ** changing them. We have to do some funky casting in order to
83075 ** initialize those fields.
83076 */
83077 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
83078 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
83079 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
83080 *(int*)&pIdxInfo->nConstraint = nTerm;
83081 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
83082 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
83083 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
83084 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
83085 pUsage;
83086
83087 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
83088 if( pTerm->leftCursor != pSrc->iCursor ) continue;
83089 assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
83090 testcase( pTerm->eOperator==WO_IN );
83091 testcase( pTerm->eOperator==WO_ISNULL );
83092 if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
83093 pIdxCons[j].iColumn = pTerm->u.leftColumn;
83094 pIdxCons[j].iTermOffset = i;
83095 pIdxCons[j].op = (u8)pTerm->eOperator;
83096 /* The direct assignment in the previous line is possible only because
83097 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
83098 ** following asserts verify this fact. */
83099 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
83100 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
83101 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
83102 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
83103 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
83104 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
83105 assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
83106 j++;
83107 }
83108 for(i=0; i<nOrderBy; i++){
83109 Expr *pExpr = pOrderBy->a[i].pExpr;
83110 pIdxOrderBy[i].iColumn = pExpr->iColumn;
83111 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
83112 }
83113
83114 return pIdxInfo;
83115 }
83116
83117 /*
83118 ** The table object reference passed as the second argument to this function
83119 ** must represent a virtual table. This function invokes the xBestIndex()
83120 ** method of the virtual table with the sqlite3_index_info pointer passed
83121 ** as the argument.
83122 **
83123 ** If an error occurs, pParse is populated with an error message and a
83124 ** non-zero value is returned. Otherwise, 0 is returned and the output
83125 ** part of the sqlite3_index_info structure is left populated.
83126 **
83127 ** Whether or not an error is returned, it is the responsibility of the
83128 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
83129 ** that this is required.
83130 */
83131 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
83132 sqlite3_vtab *pVtab = pTab->pVtab;
83133 int i;
83134 int rc;
83135
83136 (void)sqlite3SafetyOff(pParse->db);
83137 WHERETRACE(("xBestIndex for %s\n", pTab->zName));
83138 TRACE_IDX_INPUTS(p);
83139 rc = pVtab->pModule->xBestIndex(pVtab, p);
83140 TRACE_IDX_OUTPUTS(p);
83141 (void)sqlite3SafetyOn(pParse->db);
83142
83143 if( rc!=SQLITE_OK ){
83144 if( rc==SQLITE_NOMEM ){
83145 pParse->db->mallocFailed = 1;
83146 }else if( !pVtab->zErrMsg ){
83147 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
83148 }else{
83149 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
83150 }
83151 }
83152 sqlite3DbFree(pParse->db, pVtab->zErrMsg);
83153 pVtab->zErrMsg = 0;
83154
83155 for(i=0; i<p->nConstraint; i++){
83156 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
83157 sqlite3ErrorMsg(pParse,
83158 "table %s: xBestIndex returned an invalid plan", pTab->zName);
83159 }
83160 }
83161
83162 return pParse->nErr;
83163 }
83164
83165
83166 /*
83167 ** Compute the best index for a virtual table.
83168 **
83169 ** The best index is computed by the xBestIndex method of the virtual
83170 ** table module. This routine is really just a wrapper that sets up
@@ -82376,118 +83177,43 @@
83177 ** invocations. The sqlite3_index_info structure is also used when
83178 ** code is generated to access the virtual table. The whereInfoDelete()
83179 ** routine takes care of freeing the sqlite3_index_info structure after
83180 ** everybody has finished with it.
83181 */
83182 static void bestVirtualIndex(
83183 Parse *pParse, /* The parsing context */
83184 WhereClause *pWC, /* The WHERE clause */
83185 struct SrcList_item *pSrc, /* The FROM clause term to search */
83186 Bitmask notReady, /* Mask of cursors that are not available */
83187 ExprList *pOrderBy, /* The order by clause */
83188 WhereCost *pCost, /* Lowest cost query plan */
83189 sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
83190 ){
83191 Table *pTab = pSrc->pTab;
 
83192 sqlite3_index_info *pIdxInfo;
83193 struct sqlite3_index_constraint *pIdxCons;
 
83194 struct sqlite3_index_constraint_usage *pUsage;
83195 WhereTerm *pTerm;
83196 int i, j;
83197 int nOrderBy;
83198
83199 /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
83200 ** malloc in allocateIndexInfo() fails and this function returns leaving
83201 ** wsFlags in an uninitialized state, the caller may behave unpredictably.
83202 */
83203 memset(pCost, 0, sizeof(*pCost));
83204 pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
83205
83206 /* If the sqlite3_index_info structure has not been previously
83207 ** allocated and initialized, then allocate and initialize it now.
 
83208 */
83209 pIdxInfo = *ppIdxInfo;
83210 if( pIdxInfo==0 ){
83211 *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
83212 }
83213 if( pIdxInfo==0 ){
83214 return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83215 }
83216
83217 /* At this point, the sqlite3_index_info structure that pIdxInfo points
83218 ** to will have been initialized, either during the current invocation or
83219 ** during some prior invocation. Now we just have to customize the
@@ -82498,18 +83224,11 @@
83224 /* The module name must be defined. Also, by this point there must
83225 ** be a pointer to an sqlite3_vtab structure. Otherwise
83226 ** sqlite3ViewGetColumnNames() would have picked up the error.
83227 */
83228 assert( pTab->azModuleArg && pTab->azModuleArg[0] );
83229 assert( pTab->pVtab );
 
 
 
 
 
 
 
83230
83231 /* Set the aConstraint[].usable fields and initialize all
83232 ** output variables to zero.
83233 **
83234 ** aConstraint[].usable is true for constraints where the right-hand
@@ -82545,44 +83264,41 @@
83264 pIdxInfo->needToFreeIdxStr = 0;
83265 pIdxInfo->orderByConsumed = 0;
83266 /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
83267 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
83268 nOrderBy = pIdxInfo->nOrderBy;
83269 if( !pOrderBy ){
83270 pIdxInfo->nOrderBy = 0;
83271 }
83272
83273 if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
83274 return;
83275 }
83276
83277 /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
83278 ** inital value of lowestCost in this loop. If it is, then the
83279 ** (cost<lowestCost) test below will never be true.
83280 **
83281 ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
83282 ** is defined.
83283 */
83284 if( (SQLITE_BIG_DBL/((double)2))<pIdxInfo->estimatedCost ){
83285 pCost->rCost = (SQLITE_BIG_DBL/((double)2));
83286 }else{
83287 pCost->rCost = pIdxInfo->estimatedCost;
83288 }
83289 pCost->plan.u.pVtabIdx = pIdxInfo;
83290 if( pIdxInfo && pIdxInfo->orderByConsumed ){
83291 pCost->plan.wsFlags |= WHERE_ORDERBY;
83292 }
83293 pCost->plan.nEq = 0;
83294 pIdxInfo->nOrderBy = nOrderBy;
83295
83296 /* Try to find a more efficient access pattern by using multiple indexes
83297 ** to optimize an OR expression within the WHERE clause.
83298 */
83299 bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
 
 
 
83300 }
83301 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83302
83303 /*
83304 ** Find the query plan for accessing a particular table. Write the
@@ -82610,11 +83326,11 @@
83326 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
83327 ** in the SELECT statement, then no indexes are considered. However, the
83328 ** selected plan may still take advantage of the tables built-in rowid
83329 ** index.
83330 */
83331 static void bestBtreeIndex(
83332 Parse *pParse, /* The parsing context */
83333 WhereClause *pWC, /* The WHERE clause */
83334 struct SrcList_item *pSrc, /* The FROM clause term to search */
83335 Bitmask notReady, /* Mask of cursors that are not available */
83336 ExprList *pOrderBy, /* The ORDER BY clause */
@@ -82628,11 +83344,10 @@
83344 int nEq; /* Number of == or IN constraints */
83345 int eqTermMask; /* Mask of valid equality operators */
83346 double cost; /* Cost of using pProbe */
83347 double nRow; /* Estimated number of rows in result set */
83348 int i; /* Loop counter */
 
83349
83350 WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName,notReady));
83351 pProbe = pSrc->pTab->pIndex;
83352 if( pSrc->notIndexed ){
83353 pProbe = 0;
@@ -82744,65 +83459,11 @@
83459 pCost->nRow = nRow;
83460 pCost->plan.wsFlags = wsFlags;
83461 }
83462 }
83463
83464 bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83465
83466 /* If the pSrc table is the right table of a LEFT JOIN then we may not
83467 ** use an index to satisfy IS NULL constraints on that table. This is
83468 ** because columns might end up being NULL if the table does not match -
83469 ** a circumstance which the index cannot help us discover. Ticket #2177.
@@ -82823,13 +83484,14 @@
83484 int inMultIsEst = 0; /* True if inMultiplier is an estimate */
83485
83486 WHERETRACE(("... index %s:\n", pProbe->zName));
83487
83488 /* Count the number of columns in the index that are satisfied
83489 ** by x=EXPR or x IS NULL constraints or x IN (...) constraints.
83490 ** For a term of the form x=EXPR or x IS NULL we only have to do
83491 ** a single binary search. But for x IN (...) we have to do a
83492 ** number of binary searched
83493 ** equal to the number of entries on the RHS of the IN operator.
83494 ** The inMultipler variable with try to estimate the number of
83495 ** binary searches needed.
83496 */
83497 wsFlags = 0;
@@ -82845,10 +83507,12 @@
83507 inMultiplier *= 25;
83508 inMultIsEst = 1;
83509 }else if( pExpr->x.pList ){
83510 inMultiplier *= pExpr->x.pList->nExpr + 1;
83511 }
83512 }else if( pTerm->eOperator & WO_ISNULL ){
83513 wsFlags |= WHERE_COLUMN_NULL;
83514 }
83515 }
83516 nRow = pProbe->aiRowEst[i] * inMultiplier;
83517 /* If inMultiplier is an estimate and that estimate results in an
83518 ** nRow it that is more than half number of rows in the table,
@@ -82857,13 +83521,16 @@
83521 nRow = pProbe->aiRowEst[0]/2;
83522 inMultiplier = nRow/pProbe->aiRowEst[i];
83523 }
83524 cost = nRow + inMultiplier*estLog(pProbe->aiRowEst[0]);
83525 nEq = i;
83526 if( pProbe->onError!=OE_None && nEq==pProbe->nColumn ){
83527 testcase( wsFlags & WHERE_COLUMN_IN );
83528 testcase( wsFlags & WHERE_COLUMN_NULL );
83529 if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
83530 wsFlags |= WHERE_UNIQUE;
83531 }
83532 }
83533 WHERETRACE(("...... nEq=%d inMult=%.9g nRow=%.9g cost=%.9g\n",
83534 nEq, inMultiplier, nRow, cost));
83535
83536 /* Look for range constraints. Assume that each range constraint
@@ -82890,12 +83557,13 @@
83557 }
83558
83559 /* Add the additional cost of sorting if that is a factor.
83560 */
83561 if( pOrderBy ){
83562 if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
83563 && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
83564 ){
83565 if( wsFlags==0 ){
83566 wsFlags = WHERE_COLUMN_RANGE;
83567 }
83568 wsFlags |= WHERE_ORDERBY;
83569 if( rev ){
@@ -82952,10 +83620,35 @@
83620 (pCost->plan.wsFlags & WHERE_INDEXED)!=0 ?
83621 pCost->plan.u.pIdx->zName : "(none)", pCost->nRow,
83622 pCost->rCost, pCost->plan.wsFlags, pCost->plan.nEq));
83623 }
83624
83625 /*
83626 ** Find the query plan for accessing table pSrc->pTab. Write the
83627 ** best query plan and its cost into the WhereCost object supplied
83628 ** as the last parameter. This function may calculate the cost of
83629 ** both real and virtual table scans.
83630 */
83631 static void bestIndex(
83632 Parse *pParse, /* The parsing context */
83633 WhereClause *pWC, /* The WHERE clause */
83634 struct SrcList_item *pSrc, /* The FROM clause term to search */
83635 Bitmask notReady, /* Mask of cursors that are not available */
83636 ExprList *pOrderBy, /* The ORDER BY clause */
83637 WhereCost *pCost /* Lowest cost query plan */
83638 ){
83639 if( IsVirtual(pSrc->pTab) ){
83640 sqlite3_index_info *p = 0;
83641 bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
83642 if( p->needToFreeIdxStr ){
83643 sqlite3_free(p->idxStr);
83644 }
83645 sqlite3DbFree(pParse->db, p);
83646 }else{
83647 bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
83648 }
83649 }
83650
83651 /*
83652 ** Disable a term in the WHERE clause. Except, do not disable the term
83653 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
83654 ** or USING clause of that join.
@@ -83148,37 +83841,18 @@
83841 }
83842 }
83843 return regBase;
83844 }
83845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83846 /*
83847 ** Generate code for the start of the iLevel-th loop in the WHERE clause
83848 ** implementation described by pWInfo.
83849 */
83850 static Bitmask codeOneLoopStart(
83851 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
83852 int iLevel, /* Which level of pWInfo->a[] should be coded */
83853 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
83854 Bitmask notReady /* Which tables are currently available */
83855 ){
83856 int j, k; /* Loop counters */
83857 int iCur; /* The VDBE cursor for the table */
83858 int addrNxt; /* Where to jump to continue with the next IN case */
@@ -83190,24 +83864,22 @@
83864 Parse *pParse; /* Parsing context */
83865 Vdbe *v; /* The prepared stmt under constructions */
83866 struct SrcList_item *pTabItem; /* FROM clause term being coded */
83867 int addrBrk; /* Jump here to break out of the loop */
83868 int addrCont; /* Jump here to continue with next cycle */
83869 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
83870 int iReleaseReg = 0; /* Temp register to free before returning */
 
83871
83872 pParse = pWInfo->pParse;
83873 v = pParse->pVdbe;
83874 pWC = pWInfo->pWC;
83875 pLevel = &pWInfo->a[iLevel];
83876 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
83877 iCur = pTabItem->iCursor;
83878 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
83879 omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
83880 && (wctrlFlags & WHERE_FORCE_TABLE)==0;
 
83881
83882 /* Create labels for the "break" and "continue" instructions
83883 ** for the current loop. Jump to addrBrk to break out of a loop.
83884 ** Jump to cont to go immediately to the next iteration of the
83885 ** loop.
@@ -83242,24 +83914,20 @@
83914 pVtabIdx->aConstraintUsage;
83915 const struct sqlite3_index_constraint *aConstraint =
83916 pVtabIdx->aConstraint;
83917
83918 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
 
83919 for(j=1; j<=nConstraint; j++){
83920 for(k=0; k<nConstraint; k++){
83921 if( aUsage[k].argvIndex==j ){
83922 int iTerm = aConstraint[k].iTermOffset;
 
83923 sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
83924 break;
83925 }
83926 }
83927 if( k==nConstraint ) break;
83928 }
 
 
83929 sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
83930 sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
83931 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
83932 pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
83933 pVtabIdx->needToFreeIdxStr = 0;
@@ -83270,15 +83938,10 @@
83938 }
83939 }
83940 pLevel->op = OP_VNext;
83941 pLevel->p1 = iCur;
83942 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
 
 
 
 
 
83943 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
83944 }else
83945 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83946
83947 if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
@@ -83285,26 +83948,21 @@
83948 /* Case 1: We can directly reference a single row using an
83949 ** equality comparison against the ROWID field. Or
83950 ** we reference multiple rows using a "rowid IN (...)"
83951 ** construct.
83952 */
83953 iReleaseReg = sqlite3GetTempReg(pParse);
 
83954 pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
83955 assert( pTerm!=0 );
83956 assert( pTerm->pExpr!=0 );
83957 assert( pTerm->leftCursor==iCur );
83958 assert( omitTable==0 );
83959 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
83960 addrNxt = pLevel->addrNxt;
83961 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
83962 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
83963 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
 
 
 
 
83964 VdbeComment((v, "pk"));
83965 pLevel->op = OP_Noop;
83966 }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
83967 /* Case 2: We have an inequality comparison against the ROWID field.
83968 */
@@ -83367,22 +84025,16 @@
84025 start = sqlite3VdbeCurrentAddr(v);
84026 pLevel->op = bRev ? OP_Prev : OP_Next;
84027 pLevel->p1 = iCur;
84028 pLevel->p2 = start;
84029 pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
84030 if( testOp!=OP_Noop ){
84031 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
84032 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
84033 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
84034 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
84035 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
 
 
 
 
 
 
84036 }
84037 }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
84038 /* Case 3: A scan using an index.
84039 **
84040 ** The WHERE clause may contain zero or more equality
@@ -83503,16 +84155,11 @@
84155 start_constraints = pRangeStart || nEq>0;
84156
84157 /* Seek the index cursor to the start of the range. */
84158 nConstraint = nEq;
84159 if( pRangeStart ){
 
 
 
 
84160 sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq);
 
84161 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
84162 nConstraint++;
84163 }else if( isMinQuery ){
84164 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
84165 nConstraint++;
@@ -83534,10 +84181,11 @@
84181 /* Load the value for the inequality constraint at the end of the
84182 ** range (if any).
84183 */
84184 nConstraint = nEq;
84185 if( pRangeEnd ){
84186 sqlite3ExprCacheRemove(pParse, regBase+nEq);
84187 sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq);
84188 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
84189 codeApplyAffinity(pParse, regBase, nEq+1, pIdx);
84190 nConstraint++;
84191 }
@@ -83565,24 +84213,21 @@
84213 testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
84214 if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
84215 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
84216 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
84217 }
84218 sqlite3ReleaseTempReg(pParse, r1);
84219
84220 /* Seek the table cursor, if required */
84221 disableTerm(pLevel, pRangeStart);
84222 disableTerm(pLevel, pRangeEnd);
84223 if( !omitTable ){
84224 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
84225 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
84226 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
84227 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
84228 }
 
 
 
 
84229
84230 /* Record the instruction used to terminate the loop. Disable
84231 ** WHERE clause terms made redundant by the index range scan.
84232 */
84233 pLevel->op = bRev ? OP_Prev : OP_Next;
@@ -83601,70 +84246,110 @@
84246 ** CREATE INDEX i3 ON t1(c);
84247 **
84248 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
84249 **
84250 ** In the example, there are three indexed terms connected by OR.
84251 ** The top of the loop looks like this:
84252 **
84253 ** Null 1 # Zero the rowset in reg 1
84254 **
84255 ** Then, for each indexed term, the following. The arguments to
84256 ** RowSetTest are such that the rowid of the current row is inserted
84257 ** into the RowSet. If it is already present, control skips the
84258 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
84259 **
84260 ** sqlite3WhereBegin(<term>)
84261 ** RowSetTest # Insert rowid into rowset
84262 ** Gosub 2 A
84263 ** sqlite3WhereEnd()
84264 **
84265 ** Following the above, code to terminate the loop. Label A, the target
84266 ** of the Gosub above, jumps to the instruction right after the Goto.
84267 **
84268 ** Null 1 # Zero the rowset in reg 1
84269 ** Goto B # The loop is finished.
84270 **
84271 ** A: <loop body> # Return data, whatever.
84272 **
84273 ** Return 2 # Jump back to the Gosub
84274 **
84275 ** B: <after the loop>
84276 **
84277 */
84278 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
84279 WhereTerm *pFinal; /* Final subterm within the OR-clause. */
84280 SrcList oneTab; /* Shortened table list */
84281
84282 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
84283 int regRowset; /* Register for RowSet object */
84284 int regRowid; /* Register holding rowid */
84285 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
84286 int iRetInit; /* Address of regReturn init */
84287 int ii;
84288
84289 pTerm = pLevel->plan.u.pTerm;
84290 assert( pTerm!=0 );
84291 assert( pTerm->eOperator==WO_OR );
84292 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
84293 pOrWc = &pTerm->u.pOrInfo->wc;
84294 pFinal = &pOrWc->a[pOrWc->nTerm-1];
84295
84296 /* Set up a SrcList containing just the table being scanned by this loop. */
 
 
 
 
 
84297 oneTab.nSrc = 1;
84298 oneTab.nAlloc = 1;
84299 oneTab.a[0] = *pTabItem;
84300
84301 /* Initialize the rowset register to contain NULL. An SQL NULL is
84302 ** equivalent to an empty rowset.
84303 **
84304 ** Also initialize regReturn to contain the address of the instruction
84305 ** immediately following the OP_Return at the bottom of the loop. This
84306 ** is required in a few obscure LEFT JOIN cases where control jumps
84307 ** over the top of the loop into the body of it. In this case the
84308 ** correct response for the end-of-loop code (the OP_Return) is to
84309 ** fall through to the next instruction, just as an OP_Next does if
84310 ** called on an uninitialized cursor.
84311 */
84312 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
84313 regRowset = ++pParse->nMem;
84314 regRowid = ++pParse->nMem;
84315 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
84316 }
84317 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
84318
84319 for(ii=0; ii<pOrWc->nTerm; ii++){
84320 WhereTerm *pOrTerm = &pOrWc->a[ii];
84321 if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
84322 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
84323
84324 /* Loop through table entries that match term pOrTerm. */
84325 pSubWInfo = sqlite3WhereBegin(pParse, &oneTab, pOrTerm->pExpr, 0,
84326 WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE | WHERE_FORCE_TABLE);
84327 if( pSubWInfo ){
84328 if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
84329 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
84330 int r;
84331 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
84332 regRowid, 0);
84333 sqlite3VdbeAddOp4(v, OP_RowSetTest, regRowset,
84334 sqlite3VdbeCurrentAddr(v)+2,
84335 r, SQLITE_INT_TO_PTR(iSet), P4_INT32);
84336 }
84337 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
84338
84339 /* Finish the loop through table entries that match term pOrTerm. */
84340 sqlite3WhereEnd(pSubWInfo);
84341 }
84342 }
84343 }
84344 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
84345 /* sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); */
84346 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
84347 sqlite3VdbeResolveLabel(v, iLoopBody);
84348
84349 pLevel->op = OP_Return;
84350 pLevel->p1 = regReturn;
84351 disableTerm(pLevel, pTerm);
84352 }else
84353 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
84354
84355 {
@@ -83677,11 +84362,10 @@
84362 assert( omitTable==0 );
84363 pLevel->op = aStep[bRev];
84364 pLevel->p1 = iCur;
84365 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
84366 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
 
84367 }
84368 notReady &= ~getMask(pWC->pMaskSet, iCur);
84369
84370 /* Insert code to test every subexpression that can be completely
84371 ** computed using the current set of tables.
@@ -83696,13 +84380,11 @@
84380 pE = pTerm->pExpr;
84381 assert( pE!=0 );
84382 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
84383 continue;
84384 }
 
84385 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
 
84386 k = 1;
84387 pTerm->wtFlags |= TERM_CODED;
84388 }
84389
84390 /* For a LEFT OUTER JOIN, generate code that will record the fact that
@@ -83710,12 +84392,11 @@
84392 */
84393 if( pLevel->iLeftJoin ){
84394 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
84395 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
84396 VdbeComment((v, "record LEFT JOIN hit"));
84397 sqlite3ExprCacheClear(pParse);
 
84398 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
84399 testcase( pTerm->wtFlags & TERM_VIRTUAL );
84400 testcase( pTerm->wtFlags & TERM_CODED );
84401 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
84402 if( (pTerm->prereqAll & notReady)!=0 ) continue;
@@ -83722,28 +84403,11 @@
84403 assert( pTerm->pExpr );
84404 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
84405 pTerm->wtFlags |= TERM_CODED;
84406 }
84407 }
84408 sqlite3ReleaseTempReg(pParse, iReleaseReg);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84409
84410 return notReady;
84411 }
84412
84413 #if defined(SQLITE_TEST)
@@ -83766,11 +84430,11 @@
84430 if( pWInfo ){
84431 int i;
84432 for(i=0; i<pWInfo->nLevel; i++){
84433 sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
84434 if( pInfo ){
84435 /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
84436 if( pInfo->needToFreeIdxStr ){
84437 sqlite3_free(pInfo->idxStr);
84438 }
84439 sqlite3DbFree(db, pInfo);
84440 }
@@ -83872,12 +84536,11 @@
84536 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
84537 Parse *pParse, /* The parser context */
84538 SrcList *pTabList, /* A list of all tables to be scanned */
84539 Expr *pWhere, /* The WHERE clause */
84540 ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
84541 u16 wctrlFlags /* One of the WHERE_* flags defined in sqliteInt.h */
 
84542 ){
84543 int i; /* Loop counter */
84544 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
84545 WhereInfo *pWInfo; /* Will become the return value of this function */
84546 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
@@ -83887,24 +84550,19 @@
84550 struct SrcList_item *pTabItem; /* A single entry from pTabList */
84551 WhereLevel *pLevel; /* A single level in the pWInfo list */
84552 int iFrom; /* First unused FROM clause element */
84553 int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */
84554 sqlite3 *db; /* Database connection */
 
84555
84556 /* The number of tables in the FROM clause is limited by the number of
84557 ** bits in a Bitmask
84558 */
84559 if( pTabList->nSrc>BMS ){
84560 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
84561 return 0;
84562 }
84563
 
 
 
 
84564 /* Allocate and initialize the WhereInfo structure that will become the
84565 ** return value. A single allocation is used to store the WhereInfo
84566 ** struct, the contents of WhereInfo.a[], the WhereClause structure
84567 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
84568 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
@@ -83922,11 +84580,10 @@
84580 }
84581 pWInfo->nLevel = pTabList->nSrc;
84582 pWInfo->pParse = pParse;
84583 pWInfo->pTabList = pTabList;
84584 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
 
84585 pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
84586 pWInfo->wctrlFlags = wctrlFlags;
84587 pMaskSet = (WhereMaskSet*)&pWC[1];
84588
84589 /* Split the WHERE clause into separate subexpressions where each
@@ -84009,48 +84666,32 @@
84666 int once = 0; /* True when first table is seen */
84667
84668 memset(&bestPlan, 0, sizeof(bestPlan));
84669 bestPlan.rCost = SQLITE_BIG_DBL;
84670 for(j=iFrom, pTabItem=&pTabList->a[j]; j<pTabList->nSrc; j++, pTabItem++){
84671 int doNotReorder; /* True if this table should not be reordered */
84672 WhereCost sCost; /* Cost information from best[Virtual]Index() */
84673 ExprList *pOrderBy; /* ORDER BY clause for index to optimize */
84674
84675 doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
84676 if( once && doNotReorder ) break;
84677 m = getMask(pMaskSet, pTabItem->iCursor);
84678 if( (m & notReady)==0 ){
84679 if( j==iFrom ) iFrom++;
84680 continue;
84681 }
84682 pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
84683
84684 assert( pTabItem->pTab );
84685 #ifndef SQLITE_OMIT_VIRTUALTABLE
84686 if( IsVirtual(pTabItem->pTab) ){
84687 sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
84688 bestVirtualIndex(pParse, pWC, pTabItem, notReady, pOrderBy, &sCost, pp);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84689 }else
84690 #endif
84691 {
84692 bestBtreeIndex(pParse, pWC, pTabItem, notReady, pOrderBy, &sCost);
 
84693 }
84694 if( once==0 || sCost.rCost<bestPlan.rCost ){
84695 once = 1;
84696 bestPlan = sCost;
84697 bestJ = j;
@@ -84091,11 +84732,11 @@
84732 assert( bestPlan.plan.u.pIdx==pIdx );
84733 }
84734 }
84735 }
84736 WHERETRACE(("*** Optimizer Finished ***\n"));
84737 if( pParse->nErr || db->mallocFailed ){
84738 goto whereBeginError;
84739 }
84740
84741 /* If the total query only selects a single row, then the ORDER BY
84742 ** clause is irrelevant.
@@ -84274,11 +84915,11 @@
84915 SrcList *pTabList = pWInfo->pTabList;
84916 sqlite3 *db = pParse->db;
84917
84918 /* Generate loop termination code.
84919 */
84920 sqlite3ExprCacheClear(pParse);
84921 for(i=pTabList->nSrc-1; i>=0; i--){
84922 pLevel = &pWInfo->a[i];
84923 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
84924 if( pLevel->op!=OP_Noop ){
84925 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
@@ -84301,11 +84942,15 @@
84942 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
84943 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
84944 if( pLevel->iIdxCur>=0 ){
84945 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
84946 }
84947 if( pLevel->op==OP_Return ){
84948 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
84949 }else{
84950 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
84951 }
84952 sqlite3VdbeJumpHere(v, addr);
84953 }
84954 }
84955
84956 /* The "break" point is here, just past the end of the outer loop.
@@ -86511,10 +87156,12 @@
87156 break;
87157 case 36: /* column ::= columnid type carglist */
87158 {
87159 yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
87160 yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
87161 yygotominor.yy0.quoted = 0;
87162 yygotominor.yy0.dyn = 0;
87163 }
87164 break;
87165 case 37: /* columnid ::= nm */
87166 {
87167 sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
@@ -87661,11 +88308,11 @@
88308 **
88309 ** This file contains C code that splits an SQL input string up into
88310 ** individual tokens and sends those tokens one-by-one over to the
88311 ** parser for analysis.
88312 **
88313 ** $Id: tokenize.c,v 1.156 2009/05/01 21:13:37 drh Exp $
88314 */
88315
88316 /*
88317 ** The charMap() macro maps alphabetic characters into their
88318 ** lower-case ASCII equivalent. On ASCII machines, this is just
@@ -88327,14 +88974,16 @@
88974 assert( pParse->nVarExpr==0 );
88975 assert( pParse->nVarExprAlloc==0 );
88976 assert( pParse->apVarExpr==0 );
88977 enableLookaside = db->lookaside.bEnabled;
88978 if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
88979 pParse->sLastToken.quoted = 1;
88980 while( !db->mallocFailed && zSql[i]!=0 ){
88981 assert( i>=0 );
88982 pParse->sLastToken.z = (u8*)&zSql[i];
88983 assert( pParse->sLastToken.dyn==0 );
88984 assert( pParse->sLastToken.quoted );
88985 pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
88986 i += pParse->sLastToken.n;
88987 if( i>mxSqlLen ){
88988 pParse->rc = SQLITE_TOOBIG;
88989 break;
@@ -88454,11 +89103,11 @@
89103 ** This file contains C code that implements the sqlite3_complete() API.
89104 ** This code used to be part of the tokenizer.c source file. But by
89105 ** separating it out, the code will be automatically omitted from
89106 ** static links that do not use it.
89107 **
89108 ** $Id: complete.c,v 1.8 2009/04/28 04:46:42 drh Exp $
89109 */
89110 #ifndef SQLITE_OMIT_COMPLETE
89111
89112 /*
89113 ** This is defined in tokenize.c. We just have to import the definition.
@@ -88549,11 +89198,11 @@
89198 static const u8 trans[7][8] = {
89199 /* Token: */
89200 /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
89201 /* 0 START: */ { 0, 0, 1, 2, 3, 1, 1, 1, },
89202 /* 1 NORMAL: */ { 0, 1, 1, 1, 1, 1, 1, 1, },
89203 /* 2 EXPLAIN: */ { 0, 2, 2, 1, 3, 1, 1, 1, },
89204 /* 3 CREATE: */ { 0, 3, 1, 1, 1, 3, 4, 1, },
89205 /* 4 TRIGGER: */ { 5, 4, 4, 4, 4, 4, 4, 4, },
89206 /* 5 SEMI: */ { 5, 5, 4, 4, 4, 4, 4, 6, },
89207 /* 6 END: */ { 0, 6, 4, 4, 4, 4, 4, 4, },
89208 };
@@ -88731,11 +89380,11 @@
89380 ** Main file for the SQLite library. The routines in this file
89381 ** implement the programmer interface to the library. Routines in
89382 ** other files are for internal use by SQLite and should not be
89383 ** accessed by users of the library.
89384 **
89385 ** $Id: main.c,v 1.548 2009/05/06 19:03:14 drh Exp $
89386 */
89387
89388 #ifdef SQLITE_ENABLE_FTS3
89389 /************** Include fts3.h in the middle of main.c ***********************/
89390 /************** Begin file fts3.h ********************************************/
@@ -88966,18 +89615,20 @@
89615 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
89616 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
89617 sqlite3GlobalConfig.inProgress = 1;
89618 memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
89619 sqlite3RegisterGlobalFunctions();
89620 rc = sqlite3PcacheInitialize();
89621 if( rc==SQLITE_OK ){
89622 rc = sqlite3_os_init();
89623 }
89624 if( rc==SQLITE_OK ){
89625 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
89626 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
89627 sqlite3GlobalConfig.isInit = 1;
89628 }
89629 sqlite3GlobalConfig.inProgress = 0;
 
89630 }
89631 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
89632
89633 /* Go back under the static mutex and clean up the recursive
89634 ** mutex to prevent a resource leak.
@@ -89015,22 +89666,24 @@
89666
89667 /*
89668 ** Undo the effects of sqlite3_initialize(). Must not be called while
89669 ** there are outstanding database connections or memory allocations or
89670 ** while any part of SQLite is otherwise in use in any thread. This
89671 ** routine is not threadsafe. But it is safe to invoke this routine
89672 ** on when SQLite is already shut down. If SQLite is already shut down
89673 ** when this routine is invoked, then this routine is a harmless no-op.
89674 */
89675 SQLITE_API int sqlite3_shutdown(void){
 
 
89676 if( sqlite3GlobalConfig.isInit ){
89677 sqlite3GlobalConfig.isMallocInit = 0;
89678 sqlite3PcacheShutdown();
89679 sqlite3_os_end();
89680 sqlite3_reset_auto_extension();
89681 sqlite3MallocEnd();
89682 sqlite3MutexEnd();
89683 sqlite3GlobalConfig.isInit = 0;
89684 }
 
 
 
 
89685 return SQLITE_OK;
89686 }
89687
89688 /*
89689 ** This API allows applications to modify the global configuration of
@@ -89538,41 +90191,45 @@
90191 /*
90192 ** Return a static string that describes the kind of error specified in the
90193 ** argument.
90194 */
90195 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
90196 static const char* const aMsg[] = {
90197 /* SQLITE_OK */ "not an error",
90198 /* SQLITE_ERROR */ "SQL logic error or missing database",
90199 /* SQLITE_INTERNAL */ 0,
90200 /* SQLITE_PERM */ "access permission denied",
90201 /* SQLITE_ABORT */ "callback requested query abort",
90202 /* SQLITE_BUSY */ "database is locked",
90203 /* SQLITE_LOCKED */ "database table is locked",
90204 /* SQLITE_NOMEM */ "out of memory",
90205 /* SQLITE_READONLY */ "attempt to write a readonly database",
90206 /* SQLITE_INTERRUPT */ "interrupted",
90207 /* SQLITE_IOERR */ "disk I/O error",
90208 /* SQLITE_CORRUPT */ "database disk image is malformed",
90209 /* SQLITE_NOTFOUND */ 0,
90210 /* SQLITE_FULL */ "database or disk is full",
90211 /* SQLITE_CANTOPEN */ "unable to open database file",
90212 /* SQLITE_PROTOCOL */ 0,
90213 /* SQLITE_EMPTY */ "table contains no data",
90214 /* SQLITE_SCHEMA */ "database schema has changed",
90215 /* SQLITE_TOOBIG */ "String or BLOB exceeded size limit",
90216 /* SQLITE_CONSTRAINT */ "constraint failed",
90217 /* SQLITE_MISMATCH */ "datatype mismatch",
90218 /* SQLITE_MISUSE */ "library routine called out of sequence",
90219 /* SQLITE_NOLFS */ "large file support is disabled",
90220 /* SQLITE_AUTH */ "authorization denied",
90221 /* SQLITE_FORMAT */ "auxiliary database format error",
90222 /* SQLITE_RANGE */ "bind or column index out of range",
90223 /* SQLITE_NOTADB */ "file is encrypted or is not a database",
90224 };
90225 rc &= 0xff;
90226 if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
90227 return aMsg[rc];
90228 }else{
90229 return "unknown error";
90230 }
90231 }
90232
90233 /*
90234 ** This routine implements a busy callback that sleeps and tries
90235 ** again until a timeout value is reached. The timeout value is
@@ -89726,11 +90383,11 @@
90383 if( zFunctionName==0 ||
90384 (xFunc && (xFinal || xStep)) ||
90385 (!xFunc && (xFinal && !xStep)) ||
90386 (!xFunc && (!xFinal && xStep)) ||
90387 (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
90388 (255<(nName = sqlite3Strlen30( zFunctionName))) ){
90389 sqlite3Error(db, SQLITE_ERROR, "bad parameters");
90390 return SQLITE_ERROR;
90391 }
90392
90393 #ifndef SQLITE_OMIT_UTF16
@@ -89852,11 +90509,11 @@
90509 SQLITE_API int sqlite3_overload_function(
90510 sqlite3 *db,
90511 const char *zName,
90512 int nArg
90513 ){
90514 int nName = sqlite3Strlen30(zName);
90515 int rc;
90516 sqlite3_mutex_enter(db->mutex);
90517 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
90518 sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
90519 0, sqlite3InvalidFunction, 0, 0);
@@ -89960,10 +90617,43 @@
90617 db->xRollbackCallback = xCallback;
90618 db->pRollbackArg = pArg;
90619 sqlite3_mutex_leave(db->mutex);
90620 return pRet;
90621 }
90622
90623 /*
90624 ** This function returns true if main-memory should be used instead of
90625 ** a temporary file for transient pager files and statement journals.
90626 ** The value returned depends on the value of db->temp_store (runtime
90627 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
90628 ** following table describes the relationship between these two values
90629 ** and this functions return value.
90630 **
90631 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
90632 ** ----------------- -------------- ------------------------------
90633 ** 0 any file (return 0)
90634 ** 1 1 file (return 0)
90635 ** 1 2 memory (return 1)
90636 ** 1 0 file (return 0)
90637 ** 2 1 file (return 0)
90638 ** 2 2 memory (return 1)
90639 ** 2 0 memory (return 1)
90640 ** 3 any memory (return 1)
90641 */
90642 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
90643 #if SQLITE_TEMP_STORE==1
90644 return ( db->temp_store==2 );
90645 #endif
90646 #if SQLITE_TEMP_STORE==2
90647 return ( db->temp_store!=1 );
90648 #endif
90649 #if SQLITE_TEMP_STORE==3
90650 return 1;
90651 #else
90652 return 0;
90653 #endif
90654 }
90655
90656 /*
90657 ** This routine is called to create a connection to a database BTree
90658 ** driver. If zFilename is the name of a file, then that file is
90659 ** opened and used. If zFilename is the magic name ":memory:" then
@@ -89971,24 +90661,12 @@
90661 ** the connection is closed.) If zFilename is NULL then the database
90662 ** is a "virtual" database for transient use only and is deleted as
90663 ** soon as the connection is closed.
90664 **
90665 ** A virtual database can be either a disk file (that is automatically
90666 ** deleted when the file is closed) or it an be held entirely in memory.
90667 ** The sqlite3TempInMemory() function is used to determine which.
 
 
 
 
 
 
 
 
 
 
 
 
90668 */
90669 SQLITE_PRIVATE int sqlite3BtreeFactory(
90670 const sqlite3 *db, /* Main database when opening aux otherwise 0 */
90671 const char *zFilename, /* Name of the file containing the BTree database */
90672 int omitJournal, /* if TRUE then do not journal this file */
@@ -90005,26 +90683,15 @@
90683 btFlags |= BTREE_OMIT_JOURNAL;
90684 }
90685 if( db->flags & SQLITE_NoReadlock ){
90686 btFlags |= BTREE_NO_READLOCK;
90687 }
 
 
 
 
90688 #ifndef SQLITE_OMIT_MEMORYDB
90689 if( zFilename==0 && sqlite3TempInMemory(db) ){
 
 
 
 
 
 
90690 zFilename = ":memory:";
90691 }
90692 #endif
 
 
90693
90694 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
90695 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
90696 }
90697 rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
@@ -90156,23 +90823,25 @@
90823
90824 /* If SQLITE_UTF16 is specified as the encoding type, transform this
90825 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
90826 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
90827 */
90828 enc2 = enc;
90829 testcase( enc2==SQLITE_UTF16 );
90830 testcase( enc2==SQLITE_UTF16_ALIGNED );
90831 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
90832 enc2 = SQLITE_UTF16NATIVE;
90833 }
90834 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
90835 return SQLITE_MISUSE;
90836 }
90837
90838 /* Check if this call is removing or replacing an existing collation
90839 ** sequence. If so, and there are active VMs, return busy. If there
90840 ** are no active VMs, invalidate any pre-compiled statements.
90841 */
90842 nName = sqlite3Strlen30(zName);
90843 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 0);
90844 if( pColl && pColl->xCmp ){
90845 if( db->activeVdbeCnt ){
90846 sqlite3Error(db, SQLITE_BUSY,
90847 "unable to delete/modify collation sequence due to active statements");
@@ -90305,10 +90974,11 @@
90974 sqlite3 *db;
90975 int rc;
90976 CollSeq *pColl;
90977 int isThreadsafe;
90978
90979 *ppDb = 0;
90980 #ifndef SQLITE_OMIT_AUTOINIT
90981 rc = sqlite3_initialize();
90982 if( rc ) return rc;
90983 #endif
90984
@@ -90364,13 +91034,13 @@
91034 #endif
91035 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
91036 | SQLITE_LoadExtension
91037 #endif
91038 ;
91039 sqlite3HashInit(&db->aCollSeq);
91040 #ifndef SQLITE_OMIT_VIRTUALTABLE
91041 sqlite3HashInit(&db->aModule);
91042 #endif
91043
91044 db->pVfs = sqlite3_vfs_find(zVfs);
91045 if( !db->pVfs ){
91046 rc = SQLITE_ERROR;
91047
+136 -106
--- src/sqlite3.h
+++ src/sqlite3.h
@@ -28,11 +28,11 @@
2828
** The name of this file under configuration management is "sqlite.h.in".
2929
** The makefile makes some minor changes to this file (such as inserting
3030
** the version number) and changes its name to "sqlite3.h" as
3131
** part of the build process.
3232
**
33
-** @(#) $Id: sqlite.h.in,v 1.440 2009/04/06 15:55:04 drh Exp $
33
+** @(#) $Id: sqlite.h.in,v 1.447 2009/04/30 15:59:56 drh Exp $
3434
*/
3535
#ifndef _SQLITE3_H_
3636
#define _SQLITE3_H_
3737
#include <stdarg.h> /* Needed for the definition of va_list */
3838
@@ -97,12 +97,12 @@
9797
**
9898
** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
9999
**
100100
** Requirements: [H10011] [H10014]
101101
*/
102
-#define SQLITE_VERSION "3.6.13"
103
-#define SQLITE_VERSION_NUMBER 3006013
102
+#define SQLITE_VERSION "3.6.14"
103
+#define SQLITE_VERSION_NUMBER 3006014
104104
105105
/*
106106
** CAPI3REF: Run-Time Library Version Numbers {H10020} <S60100>
107107
** KEYWORDS: sqlite3_version
108108
**
@@ -789,10 +789,15 @@
789789
** the process, or if it is the first time sqlite3_initialize() is invoked
790790
** following a call to sqlite3_shutdown(). Only an effective call
791791
** of sqlite3_initialize() does any initialization. All other calls
792792
** are harmless no-ops.
793793
**
794
+** A call to sqlite3_shutdown() is an "effective" call if it is the first
795
+** call to sqlite3_shutdown() since the last sqlite3_initialize(). Only
796
+** an effective call to sqlite3_shutdown() does any deinitialization.
797
+** All other calls to sqlite3_shutdown() are harmless no-ops.
798
+**
794799
** Among other things, sqlite3_initialize() shall invoke
795800
** sqlite3_os_init(). Similarly, sqlite3_shutdown()
796801
** shall invoke sqlite3_os_end().
797802
**
798803
** The sqlite3_initialize() routine returns [SQLITE_OK] on success.
@@ -1215,19 +1220,23 @@
12151220
** on the [database connection] specified by the first parameter.
12161221
** Only changes that are directly specified by the [INSERT], [UPDATE],
12171222
** or [DELETE] statement are counted. Auxiliary changes caused by
12181223
** triggers are not counted. Use the [sqlite3_total_changes()] function
12191224
** to find the total number of changes including changes caused by triggers.
1225
+**
1226
+** Changes to a view that are simulated by an [INSTEAD OF trigger]
1227
+** are not counted. Only real table changes are counted.
12201228
**
12211229
** A "row change" is a change to a single row of a single table
12221230
** caused by an INSERT, DELETE, or UPDATE statement. Rows that
1223
-** are changed as side effects of REPLACE constraint resolution,
1224
-** rollback, ABORT processing, DROP TABLE, or by any other
1231
+** are changed as side effects of [REPLACE] constraint resolution,
1232
+** rollback, ABORT processing, [DROP TABLE], or by any other
12251233
** mechanisms do not count as direct row changes.
12261234
**
12271235
** A "trigger context" is a scope of execution that begins and
1228
-** ends with the script of a trigger. Most SQL statements are
1236
+** ends with the script of a [CREATE TRIGGER | trigger].
1237
+** Most SQL statements are
12291238
** evaluated outside of any trigger. This is the "top level"
12301239
** trigger context. If a trigger fires from the top level, a
12311240
** new trigger context is entered for the duration of that one
12321241
** trigger. Subtriggers create subcontexts for their duration.
12331242
**
@@ -1245,20 +1254,12 @@
12451254
** changes in the most recently completed INSERT, UPDATE, or DELETE
12461255
** statement within the body of the same trigger.
12471256
** However, the number returned does not include changes
12481257
** caused by subtriggers since those have their own context.
12491258
**
1250
-** SQLite implements the command "DELETE FROM table" without a WHERE clause
1251
-** by dropping and recreating the table. Doing so is much faster than going
1252
-** through and deleting individual elements from the table. Because of this
1253
-** optimization, the deletions in "DELETE FROM table" are not row changes and
1254
-** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
1255
-** functions, regardless of the number of elements that were originally
1256
-** in the table. To get an accurate count of the number of rows deleted, use
1257
-** "DELETE FROM table WHERE 1" instead. Or recompile using the
1258
-** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
1259
-** optimization on all queries.
1259
+** See also the [sqlite3_total_changes()] interface and the
1260
+** [count_changes pragma].
12601261
**
12611262
** Requirements:
12621263
** [H12241] [H12243]
12631264
**
12641265
** If a separate thread makes changes on the same database connection
@@ -1268,31 +1269,25 @@
12681269
int sqlite3_changes(sqlite3*);
12691270
12701271
/*
12711272
** CAPI3REF: Total Number Of Rows Modified {H12260} <S10600>
12721273
**
1273
-** This function returns the number of row changes caused by INSERT,
1274
-** UPDATE or DELETE statements since the [database connection] was opened.
1275
-** The count includes all changes from all trigger contexts. However,
1276
-** the count does not include changes used to implement REPLACE constraints,
1277
-** do rollbacks or ABORT processing, or DROP table processing.
1274
+** This function returns the number of row changes caused by [INSERT],
1275
+** [UPDATE] or [DELETE] statements since the [database connection] was opened.
1276
+** The count includes all changes from all
1277
+** [CREATE TRIGGER | trigger] contexts. However,
1278
+** the count does not include changes used to implement [REPLACE] constraints,
1279
+** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
1280
+** count does not rows of views that fire an [INSTEAD OF trigger], though if
1281
+** the INSTEAD OF trigger makes changes of its own, those changes are
1282
+** counted.
12781283
** The changes are counted as soon as the statement that makes them is
12791284
** completed (when the statement handle is passed to [sqlite3_reset()] or
12801285
** [sqlite3_finalize()]).
12811286
**
1282
-** SQLite implements the command "DELETE FROM table" without a WHERE clause
1283
-** by dropping and recreating the table. (This is much faster than going
1284
-** through and deleting individual elements from the table.) Because of this
1285
-** optimization, the deletions in "DELETE FROM table" are not row changes and
1286
-** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
1287
-** functions, regardless of the number of elements that were originally
1288
-** in the table. To get an accurate count of the number of rows deleted, use
1289
-** "DELETE FROM table WHERE 1" instead. Or recompile using the
1290
-** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
1291
-** optimization on all queries.
1292
-**
1293
-** See also the [sqlite3_changes()] interface.
1287
+** See also the [sqlite3_changes()] interface and the
1288
+** [count_changes pragma].
12941289
**
12951290
** Requirements:
12961291
** [H12261] [H12263]
12971292
**
12981293
** If a separate thread makes changes on the same database connection
@@ -1322,12 +1317,20 @@
13221317
** An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
13231318
** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
13241319
** that is inside an explicit transaction, then the entire transaction
13251320
** will be rolled back automatically.
13261321
**
1327
-** A call to sqlite3_interrupt() has no effect on SQL statements
1328
-** that are started after sqlite3_interrupt() returns.
1322
+** The sqlite3_interrupt(D) call is in effect until all currently running
1323
+** SQL statements on [database connection] D complete. Any new SQL statements
1324
+** that are started after the sqlite3_interrupt() call and before the
1325
+** running statements reaches zero are interrupted as if they had been
1326
+** running prior to the sqlite3_interrupt() call. New SQL statements
1327
+** that are started after the running statement count reaches zero are
1328
+** not effected by the sqlite3_interrupt().
1329
+** A call to sqlite3_interrupt(D) that occurs when there are no running
1330
+** SQL statements is a no-op and has no effect on SQL statements
1331
+** that are started after the sqlite3_interrupt() call returns.
13291332
**
13301333
** Requirements:
13311334
** [H12271] [H12272]
13321335
**
13331336
** If the database connection closes while [sqlite3_interrupt()]
@@ -1336,23 +1339,33 @@
13361339
void sqlite3_interrupt(sqlite3*);
13371340
13381341
/*
13391342
** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} <S70200>
13401343
**
1341
-** These routines are useful for command-line input to determine if the
1342
-** currently entered text seems to form complete a SQL statement or
1344
+** These routines are useful during command-line input to determine if the
1345
+** currently entered text seems to form a complete SQL statement or
13431346
** if additional input is needed before sending the text into
1344
-** SQLite for parsing. These routines return true if the input string
1347
+** SQLite for parsing. These routines return 1 if the input string
13451348
** appears to be a complete SQL statement. A statement is judged to be
1346
-** complete if it ends with a semicolon token and is not a fragment of a
1347
-** CREATE TRIGGER statement. Semicolons that are embedded within
1349
+** complete if it ends with a semicolon token and is not a prefix of a
1350
+** well-formed CREATE TRIGGER statement. Semicolons that are embedded within
13481351
** string literals or quoted identifier names or comments are not
13491352
** independent tokens (they are part of the token in which they are
1350
-** embedded) and thus do not count as a statement terminator.
1353
+** embedded) and thus do not count as a statement terminator. Whitespace
1354
+** and comments that follow the final semicolon are ignored.
1355
+**
1356
+** These routines return 0 if the statement is incomplete. If a
1357
+** memory allocation fails, then SQLITE_NOMEM is returned.
13511358
**
13521359
** These routines do not parse the SQL statements thus
13531360
** will not detect syntactically incorrect SQL.
1361
+**
1362
+** If SQLite has not been initialized using [sqlite3_initialize()] prior
1363
+** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
1364
+** automatically by sqlite3_complete16(). If that initialization fails,
1365
+** then the return value from sqlite3_complete16() will be non-zero
1366
+** regardless of whether or not the input SQL is complete.
13541367
**
13551368
** Requirements: [H10511] [H10512]
13561369
**
13571370
** The input to [sqlite3_complete()] must be a zero-terminated
13581371
** UTF-8 string.
@@ -1777,25 +1790,30 @@
17771790
**
17781791
** When the callback returns [SQLITE_OK], that means the operation
17791792
** requested is ok. When the callback returns [SQLITE_DENY], the
17801793
** [sqlite3_prepare_v2()] or equivalent call that triggered the
17811794
** authorizer will fail with an error message explaining that
1782
-** access is denied. If the authorizer code is [SQLITE_READ]
1783
-** and the callback returns [SQLITE_IGNORE] then the
1784
-** [prepared statement] statement is constructed to substitute
1785
-** a NULL value in place of the table column that would have
1786
-** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
1787
-** return can be used to deny an untrusted user access to individual
1788
-** columns of a table.
1795
+** access is denied.
17891796
**
17901797
** The first parameter to the authorizer callback is a copy of the third
17911798
** parameter to the sqlite3_set_authorizer() interface. The second parameter
17921799
** to the callback is an integer [SQLITE_COPY | action code] that specifies
17931800
** the particular action to be authorized. The third through sixth parameters
17941801
** to the callback are zero-terminated strings that contain additional
17951802
** details about the action to be authorized.
17961803
**
1804
+** If the action code is [SQLITE_READ]
1805
+** and the callback returns [SQLITE_IGNORE] then the
1806
+** [prepared statement] statement is constructed to substitute
1807
+** a NULL value in place of the table column that would have
1808
+** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
1809
+** return can be used to deny an untrusted user access to individual
1810
+** columns of a table.
1811
+** If the action code is [SQLITE_DELETE] and the callback returns
1812
+** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
1813
+** [truncate optimization] is disabled and all rows are deleted individually.
1814
+**
17971815
** An authorizer is used when [sqlite3_prepare | preparing]
17981816
** SQL statements from an untrusted source, to ensure that the SQL statements
17991817
** do not try to access data they are not allowed to see, or that they do not
18001818
** try to execute malicious statements that damage the database. For
18011819
** example, an application may allow a user to enter arbitrary
@@ -1825,11 +1843,13 @@
18251843
** schema change. Hence, the application should ensure that the
18261844
** correct authorizer callback remains in place during the [sqlite3_step()].
18271845
**
18281846
** Note that the authorizer callback is invoked only during
18291847
** [sqlite3_prepare()] or its variants. Authorization is not
1830
-** performed during statement evaluation in [sqlite3_step()].
1848
+** performed during statement evaluation in [sqlite3_step()], unless
1849
+** as stated in the previous paragraph, sqlite3_step() invokes
1850
+** sqlite3_prepare_v2() to reprepare a statement after a schema change.
18311851
**
18321852
** Requirements:
18331853
** [H12501] [H12502] [H12503] [H12504] [H12505] [H12506] [H12507] [H12510]
18341854
** [H12511] [H12512] [H12520] [H12521] [H12522]
18351855
*/
@@ -3481,16 +3501,18 @@
34813501
** for sqlite3_create_collation() and sqlite3_create_collation_v2()
34823502
** and a UTF-16 string for sqlite3_create_collation16(). In all cases
34833503
** the name is passed as the second function argument.
34843504
**
34853505
** The third argument may be one of the constants [SQLITE_UTF8],
3486
-** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
3506
+** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
34873507
** routine expects to be passed pointers to strings encoded using UTF-8,
34883508
** UTF-16 little-endian, or UTF-16 big-endian, respectively. The
3489
-** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
3509
+** third argument might also be [SQLITE_UTF16] to indicate that the routine
3510
+** expects pointers to be UTF-16 strings in the native byte order, or the
3511
+** argument can be [SQLITE_UTF16_ALIGNED] if the
34903512
** the routine expects pointers to 16-bit word aligned strings
3491
-** of UTF-16 in the native byte order of the host computer.
3513
+** of UTF-16 in the native byte order.
34923514
**
34933515
** A pointer to the user supplied routine must be passed as the fifth
34943516
** argument. If it is NULL, this is the same as deleting the collation
34953517
** sequence (so that SQLite cannot call it anymore).
34963518
** Each time the application supplied function is invoked, it is passed
@@ -3510,10 +3532,12 @@
35103532
** destroyed and is passed a copy of the fourth parameter void* pointer
35113533
** of the sqlite3_create_collation_v2().
35123534
** Collations are destroyed when they are overridden by later calls to the
35133535
** collation creation functions or when the [database connection] is closed
35143536
** using [sqlite3_close()].
3537
+**
3538
+** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
35153539
**
35163540
** Requirements:
35173541
** [H16603] [H16604] [H16606] [H16609] [H16612] [H16615] [H16618] [H16621]
35183542
** [H16624] [H16627] [H16630]
35193543
*/
@@ -4064,19 +4088,24 @@
40644088
typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
40654089
typedef struct sqlite3_module sqlite3_module;
40664090
40674091
/*
40684092
** CAPI3REF: Virtual Table Object {H18000} <S20400>
4069
-** KEYWORDS: sqlite3_module
4093
+** KEYWORDS: sqlite3_module {virtual table module}
40704094
** EXPERIMENTAL
40714095
**
4072
-** A module is a class of virtual tables. Each module is defined
4073
-** by an instance of the following structure. This structure consists
4074
-** mostly of methods for the module.
4096
+** This structure, sometimes called a a "virtual table module",
4097
+** defines the implementation of a [virtual tables].
4098
+** This structure consists mostly of methods for the module.
40754099
**
4076
-** This interface is experimental and is subject to change or
4077
-** removal in future releases of SQLite.
4100
+** A virtual table module is created by filling in a persistent
4101
+** instance of this structure and passing a pointer to that instance
4102
+** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
4103
+** The registration remains valid until it is replaced by a different
4104
+** module or until the [database connection] closes. The content
4105
+** of this structure must not change while it is registered with
4106
+** any database connection.
40784107
*/
40794108
struct sqlite3_module {
40804109
int iVersion;
40814110
int (*xCreate)(sqlite3*, void *pAux,
40824111
int argc, const char *const*argv,
@@ -4110,12 +4139,12 @@
41104139
** CAPI3REF: Virtual Table Indexing Information {H18100} <S20400>
41114140
** KEYWORDS: sqlite3_index_info
41124141
** EXPERIMENTAL
41134142
**
41144143
** The sqlite3_index_info structure and its substructures is used to
4115
-** pass information into and receive the reply from the xBestIndex
4116
-** method of an sqlite3_module. The fields under **Inputs** are the
4144
+** pass information into and receive the reply from the [xBestIndex]
4145
+** method of a [virtual table module]. The fields under **Inputs** are the
41174146
** inputs to xBestIndex and are read-only. xBestIndex inserts its
41184147
** results into the **Outputs** fields.
41194148
**
41204149
** The aConstraint[] array records WHERE clause constraints of the form:
41214150
**
@@ -4134,31 +4163,30 @@
41344163
** form that refer to the particular virtual table being queried.
41354164
**
41364165
** Information about the ORDER BY clause is stored in aOrderBy[].
41374166
** Each term of aOrderBy records a column of the ORDER BY clause.
41384167
**
4139
-** The xBestIndex method must fill aConstraintUsage[] with information
4168
+** The [xBestIndex] method must fill aConstraintUsage[] with information
41404169
** about what parameters to pass to xFilter. If argvIndex>0 then
41414170
** the right-hand side of the corresponding aConstraint[] is evaluated
41424171
** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit
41434172
** is true, then the constraint is assumed to be fully handled by the
41444173
** virtual table and is not checked again by SQLite.
41454174
**
4146
-** The idxNum and idxPtr values are recorded and passed into xFilter.
4147
-** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
4175
+** The idxNum and idxPtr values are recorded and passed into the
4176
+** [xFilter] method.
4177
+** [sqlite3_free()] is used to free idxPtr if and only iff
4178
+** needToFreeIdxPtr is true.
41484179
**
4149
-** The orderByConsumed means that output from xFilter will occur in
4180
+** The orderByConsumed means that output from [xFilter]/[xNext] will occur in
41504181
** the correct order to satisfy the ORDER BY clause so that no separate
41514182
** sorting step is required.
41524183
**
41534184
** The estimatedCost value is an estimate of the cost of doing the
41544185
** particular lookup. A full scan of a table with N entries should have
41554186
** a cost of N. A binary search of a table of N entries should have a
41564187
** cost of approximately log(N).
4157
-**
4158
-** This interface is experimental and is subject to change or
4159
-** removal in future releases of SQLite.
41604188
*/
41614189
struct sqlite3_index_info {
41624190
/* Inputs */
41634191
int nConstraint; /* Number of entries in aConstraint */
41644192
struct sqlite3_index_constraint {
@@ -4192,64 +4220,69 @@
41924220
41934221
/*
41944222
** CAPI3REF: Register A Virtual Table Implementation {H18200} <S20400>
41954223
** EXPERIMENTAL
41964224
**
4197
-** This routine is used to register a new module name with a
4198
-** [database connection]. Module names must be registered before
4199
-** creating new virtual tables on the module, or before using
4200
-** preexisting virtual tables of the module.
4225
+** This routine is used to register a new [virtual table module] name.
4226
+** Module names must be registered before
4227
+** creating a new [virtual table] using the module, or before using a
4228
+** preexisting [virtual table] for the module.
42014229
**
4202
-** This interface is experimental and is subject to change or
4203
-** removal in future releases of SQLite.
4230
+** The module name is registered on the [database connection] specified
4231
+** by the first parameter. The name of the module is given by the
4232
+** second parameter. The third parameter is a pointer to
4233
+** the implementation of the [virtual table module]. The fourth
4234
+** parameter is an arbitrary client data pointer that is passed through
4235
+** into the [xCreate] and [xConnect] methods of the virtual table module
4236
+** when a new virtual table is be being created or reinitialized.
4237
+**
4238
+** This interface has exactly the same effect as calling
4239
+** [sqlite3_create_module_v2()] with a NULL client data destructor.
42044240
*/
42054241
SQLITE_EXPERIMENTAL int sqlite3_create_module(
42064242
sqlite3 *db, /* SQLite connection to register module with */
42074243
const char *zName, /* Name of the module */
4208
- const sqlite3_module *, /* Methods for the module */
4209
- void * /* Client data for xCreate/xConnect */
4244
+ const sqlite3_module *p, /* Methods for the module */
4245
+ void *pClientData /* Client data for xCreate/xConnect */
42104246
);
42114247
42124248
/*
42134249
** CAPI3REF: Register A Virtual Table Implementation {H18210} <S20400>
42144250
** EXPERIMENTAL
42154251
**
4216
-** This routine is identical to the [sqlite3_create_module()] method above,
4217
-** except that it allows a destructor function to be specified. It is
4218
-** even more experimental than the rest of the virtual tables API.
4252
+** This routine is identical to the [sqlite3_create_module()] method,
4253
+** except that it has an extra parameter to specify
4254
+** a destructor function for the client data pointer. SQLite will
4255
+** invoke the destructor function (if it is not NULL) when SQLite
4256
+** no longer needs the pClientData pointer.
42194257
*/
42204258
SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
42214259
sqlite3 *db, /* SQLite connection to register module with */
42224260
const char *zName, /* Name of the module */
4223
- const sqlite3_module *, /* Methods for the module */
4224
- void *, /* Client data for xCreate/xConnect */
4261
+ const sqlite3_module *p, /* Methods for the module */
4262
+ void *pClientData, /* Client data for xCreate/xConnect */
42254263
void(*xDestroy)(void*) /* Module destructor function */
42264264
);
42274265
42284266
/*
42294267
** CAPI3REF: Virtual Table Instance Object {H18010} <S20400>
42304268
** KEYWORDS: sqlite3_vtab
42314269
** EXPERIMENTAL
42324270
**
4233
-** Every module implementation uses a subclass of the following structure
4234
-** to describe a particular instance of the module. Each subclass will
4271
+** Every [virtual table module] implementation uses a subclass
4272
+** of the following structure to describe a particular instance
4273
+** of the [virtual table]. Each subclass will
42354274
** be tailored to the specific needs of the module implementation.
42364275
** The purpose of this superclass is to define certain fields that are
42374276
** common to all module implementations.
42384277
**
42394278
** Virtual tables methods can set an error message by assigning a
42404279
** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
42414280
** take care that any prior string is freed by a call to [sqlite3_free()]
42424281
** prior to assigning a new string to zErrMsg. After the error message
42434282
** is delivered up to the client application, the string will be automatically
4244
-** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note
4245
-** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
4246
-** since virtual tables are commonly implemented in loadable extensions which
4247
-** do not have access to sqlite3MPrintf() or sqlite3Free().
4248
-**
4249
-** This interface is experimental and is subject to change or
4250
-** removal in future releases of SQLite.
4283
+** freed by sqlite3_free() and the zErrMsg field will be zeroed.
42514284
*/
42524285
struct sqlite3_vtab {
42534286
const sqlite3_module *pModule; /* The module for this virtual table */
42544287
int nRef; /* Used internally */
42554288
char *zErrMsg; /* Error message from sqlite3_mprintf() */
@@ -4256,24 +4289,25 @@
42564289
/* Virtual table implementations will typically add additional fields */
42574290
};
42584291
42594292
/*
42604293
** CAPI3REF: Virtual Table Cursor Object {H18020} <S20400>
4261
-** KEYWORDS: sqlite3_vtab_cursor
4294
+** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
42624295
** EXPERIMENTAL
42634296
**
4264
-** Every module implementation uses a subclass of the following structure
4265
-** to describe cursors that point into the virtual table and are used
4297
+** Every [virtual table module] implementation uses a subclass of the
4298
+** following structure to describe cursors that point into the
4299
+** [virtual table] and are used
42664300
** to loop through the virtual table. Cursors are created using the
4267
-** xOpen method of the module. Each module implementation will define
4301
+** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
4302
+** by the [sqlite3_module.xClose | xClose] method. Cussors are used
4303
+** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
4304
+** of the module. Each module implementation will define
42684305
** the content of a cursor structure to suit its own needs.
42694306
**
42704307
** This superclass exists in order to define fields of the cursor that
42714308
** are common to all implementations.
4272
-**
4273
-** This interface is experimental and is subject to change or
4274
-** removal in future releases of SQLite.
42754309
*/
42764310
struct sqlite3_vtab_cursor {
42774311
sqlite3_vtab *pVtab; /* Virtual table of this cursor */
42784312
/* Virtual table implementations will typically add additional fields */
42794313
};
@@ -4280,37 +4314,33 @@
42804314
42814315
/*
42824316
** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} <S20400>
42834317
** EXPERIMENTAL
42844318
**
4285
-** The xCreate and xConnect methods of a module use the following API
4319
+** The [xCreate] and [xConnect] methods of a
4320
+** [virtual table module] call this interface
42864321
** to declare the format (the names and datatypes of the columns) of
42874322
** the virtual tables they implement.
4288
-**
4289
-** This interface is experimental and is subject to change or
4290
-** removal in future releases of SQLite.
42914323
*/
4292
-SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
4324
+SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
42934325
42944326
/*
42954327
** CAPI3REF: Overload A Function For A Virtual Table {H18300} <S20400>
42964328
** EXPERIMENTAL
42974329
**
42984330
** Virtual tables can provide alternative implementations of functions
4299
-** using the xFindFunction method. But global versions of those functions
4331
+** using the [xFindFunction] method of the [virtual table module].
4332
+** But global versions of those functions
43004333
** must exist in order to be overloaded.
43014334
**
43024335
** This API makes sure a global version of a function with a particular
43034336
** name and number of parameters exists. If no such function exists
43044337
** before this API is called, a new function is created. The implementation
43054338
** of the new function always causes an exception to be thrown. So
43064339
** the new function is not good for anything by itself. Its only
43074340
** purpose is to be a placeholder function that can be overloaded
4308
-** by virtual tables.
4309
-**
4310
-** This API should be considered part of the virtual table interface,
4311
-** which is experimental and subject to change.
4341
+** by a [virtual table].
43124342
*/
43134343
SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
43144344
43154345
/*
43164346
** The interface to the virtual-table mechanism defined above (back up
43174347
--- src/sqlite3.h
+++ src/sqlite3.h
@@ -28,11 +28,11 @@
28 ** The name of this file under configuration management is "sqlite.h.in".
29 ** The makefile makes some minor changes to this file (such as inserting
30 ** the version number) and changes its name to "sqlite3.h" as
31 ** part of the build process.
32 **
33 ** @(#) $Id: sqlite.h.in,v 1.440 2009/04/06 15:55:04 drh Exp $
34 */
35 #ifndef _SQLITE3_H_
36 #define _SQLITE3_H_
37 #include <stdarg.h> /* Needed for the definition of va_list */
38
@@ -97,12 +97,12 @@
97 **
98 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
99 **
100 ** Requirements: [H10011] [H10014]
101 */
102 #define SQLITE_VERSION "3.6.13"
103 #define SQLITE_VERSION_NUMBER 3006013
104
105 /*
106 ** CAPI3REF: Run-Time Library Version Numbers {H10020} <S60100>
107 ** KEYWORDS: sqlite3_version
108 **
@@ -789,10 +789,15 @@
789 ** the process, or if it is the first time sqlite3_initialize() is invoked
790 ** following a call to sqlite3_shutdown(). Only an effective call
791 ** of sqlite3_initialize() does any initialization. All other calls
792 ** are harmless no-ops.
793 **
 
 
 
 
 
794 ** Among other things, sqlite3_initialize() shall invoke
795 ** sqlite3_os_init(). Similarly, sqlite3_shutdown()
796 ** shall invoke sqlite3_os_end().
797 **
798 ** The sqlite3_initialize() routine returns [SQLITE_OK] on success.
@@ -1215,19 +1220,23 @@
1215 ** on the [database connection] specified by the first parameter.
1216 ** Only changes that are directly specified by the [INSERT], [UPDATE],
1217 ** or [DELETE] statement are counted. Auxiliary changes caused by
1218 ** triggers are not counted. Use the [sqlite3_total_changes()] function
1219 ** to find the total number of changes including changes caused by triggers.
 
 
 
1220 **
1221 ** A "row change" is a change to a single row of a single table
1222 ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
1223 ** are changed as side effects of REPLACE constraint resolution,
1224 ** rollback, ABORT processing, DROP TABLE, or by any other
1225 ** mechanisms do not count as direct row changes.
1226 **
1227 ** A "trigger context" is a scope of execution that begins and
1228 ** ends with the script of a trigger. Most SQL statements are
 
1229 ** evaluated outside of any trigger. This is the "top level"
1230 ** trigger context. If a trigger fires from the top level, a
1231 ** new trigger context is entered for the duration of that one
1232 ** trigger. Subtriggers create subcontexts for their duration.
1233 **
@@ -1245,20 +1254,12 @@
1245 ** changes in the most recently completed INSERT, UPDATE, or DELETE
1246 ** statement within the body of the same trigger.
1247 ** However, the number returned does not include changes
1248 ** caused by subtriggers since those have their own context.
1249 **
1250 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
1251 ** by dropping and recreating the table. Doing so is much faster than going
1252 ** through and deleting individual elements from the table. Because of this
1253 ** optimization, the deletions in "DELETE FROM table" are not row changes and
1254 ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
1255 ** functions, regardless of the number of elements that were originally
1256 ** in the table. To get an accurate count of the number of rows deleted, use
1257 ** "DELETE FROM table WHERE 1" instead. Or recompile using the
1258 ** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
1259 ** optimization on all queries.
1260 **
1261 ** Requirements:
1262 ** [H12241] [H12243]
1263 **
1264 ** If a separate thread makes changes on the same database connection
@@ -1268,31 +1269,25 @@
1268 int sqlite3_changes(sqlite3*);
1269
1270 /*
1271 ** CAPI3REF: Total Number Of Rows Modified {H12260} <S10600>
1272 **
1273 ** This function returns the number of row changes caused by INSERT,
1274 ** UPDATE or DELETE statements since the [database connection] was opened.
1275 ** The count includes all changes from all trigger contexts. However,
1276 ** the count does not include changes used to implement REPLACE constraints,
1277 ** do rollbacks or ABORT processing, or DROP table processing.
 
 
 
 
1278 ** The changes are counted as soon as the statement that makes them is
1279 ** completed (when the statement handle is passed to [sqlite3_reset()] or
1280 ** [sqlite3_finalize()]).
1281 **
1282 ** SQLite implements the command "DELETE FROM table" without a WHERE clause
1283 ** by dropping and recreating the table. (This is much faster than going
1284 ** through and deleting individual elements from the table.) Because of this
1285 ** optimization, the deletions in "DELETE FROM table" are not row changes and
1286 ** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()]
1287 ** functions, regardless of the number of elements that were originally
1288 ** in the table. To get an accurate count of the number of rows deleted, use
1289 ** "DELETE FROM table WHERE 1" instead. Or recompile using the
1290 ** [SQLITE_OMIT_TRUNCATE_OPTIMIZATION] compile-time option to disable the
1291 ** optimization on all queries.
1292 **
1293 ** See also the [sqlite3_changes()] interface.
1294 **
1295 ** Requirements:
1296 ** [H12261] [H12263]
1297 **
1298 ** If a separate thread makes changes on the same database connection
@@ -1322,12 +1317,20 @@
1322 ** An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
1323 ** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
1324 ** that is inside an explicit transaction, then the entire transaction
1325 ** will be rolled back automatically.
1326 **
1327 ** A call to sqlite3_interrupt() has no effect on SQL statements
1328 ** that are started after sqlite3_interrupt() returns.
 
 
 
 
 
 
 
 
1329 **
1330 ** Requirements:
1331 ** [H12271] [H12272]
1332 **
1333 ** If the database connection closes while [sqlite3_interrupt()]
@@ -1336,23 +1339,33 @@
1336 void sqlite3_interrupt(sqlite3*);
1337
1338 /*
1339 ** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} <S70200>
1340 **
1341 ** These routines are useful for command-line input to determine if the
1342 ** currently entered text seems to form complete a SQL statement or
1343 ** if additional input is needed before sending the text into
1344 ** SQLite for parsing. These routines return true if the input string
1345 ** appears to be a complete SQL statement. A statement is judged to be
1346 ** complete if it ends with a semicolon token and is not a fragment of a
1347 ** CREATE TRIGGER statement. Semicolons that are embedded within
1348 ** string literals or quoted identifier names or comments are not
1349 ** independent tokens (they are part of the token in which they are
1350 ** embedded) and thus do not count as a statement terminator.
 
 
 
 
1351 **
1352 ** These routines do not parse the SQL statements thus
1353 ** will not detect syntactically incorrect SQL.
 
 
 
 
 
 
1354 **
1355 ** Requirements: [H10511] [H10512]
1356 **
1357 ** The input to [sqlite3_complete()] must be a zero-terminated
1358 ** UTF-8 string.
@@ -1777,25 +1790,30 @@
1777 **
1778 ** When the callback returns [SQLITE_OK], that means the operation
1779 ** requested is ok. When the callback returns [SQLITE_DENY], the
1780 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
1781 ** authorizer will fail with an error message explaining that
1782 ** access is denied. If the authorizer code is [SQLITE_READ]
1783 ** and the callback returns [SQLITE_IGNORE] then the
1784 ** [prepared statement] statement is constructed to substitute
1785 ** a NULL value in place of the table column that would have
1786 ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
1787 ** return can be used to deny an untrusted user access to individual
1788 ** columns of a table.
1789 **
1790 ** The first parameter to the authorizer callback is a copy of the third
1791 ** parameter to the sqlite3_set_authorizer() interface. The second parameter
1792 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
1793 ** the particular action to be authorized. The third through sixth parameters
1794 ** to the callback are zero-terminated strings that contain additional
1795 ** details about the action to be authorized.
1796 **
 
 
 
 
 
 
 
 
 
 
 
1797 ** An authorizer is used when [sqlite3_prepare | preparing]
1798 ** SQL statements from an untrusted source, to ensure that the SQL statements
1799 ** do not try to access data they are not allowed to see, or that they do not
1800 ** try to execute malicious statements that damage the database. For
1801 ** example, an application may allow a user to enter arbitrary
@@ -1825,11 +1843,13 @@
1825 ** schema change. Hence, the application should ensure that the
1826 ** correct authorizer callback remains in place during the [sqlite3_step()].
1827 **
1828 ** Note that the authorizer callback is invoked only during
1829 ** [sqlite3_prepare()] or its variants. Authorization is not
1830 ** performed during statement evaluation in [sqlite3_step()].
 
 
1831 **
1832 ** Requirements:
1833 ** [H12501] [H12502] [H12503] [H12504] [H12505] [H12506] [H12507] [H12510]
1834 ** [H12511] [H12512] [H12520] [H12521] [H12522]
1835 */
@@ -3481,16 +3501,18 @@
3481 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
3482 ** and a UTF-16 string for sqlite3_create_collation16(). In all cases
3483 ** the name is passed as the second function argument.
3484 **
3485 ** The third argument may be one of the constants [SQLITE_UTF8],
3486 ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied
3487 ** routine expects to be passed pointers to strings encoded using UTF-8,
3488 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. The
3489 ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that
 
 
3490 ** the routine expects pointers to 16-bit word aligned strings
3491 ** of UTF-16 in the native byte order of the host computer.
3492 **
3493 ** A pointer to the user supplied routine must be passed as the fifth
3494 ** argument. If it is NULL, this is the same as deleting the collation
3495 ** sequence (so that SQLite cannot call it anymore).
3496 ** Each time the application supplied function is invoked, it is passed
@@ -3510,10 +3532,12 @@
3510 ** destroyed and is passed a copy of the fourth parameter void* pointer
3511 ** of the sqlite3_create_collation_v2().
3512 ** Collations are destroyed when they are overridden by later calls to the
3513 ** collation creation functions or when the [database connection] is closed
3514 ** using [sqlite3_close()].
 
 
3515 **
3516 ** Requirements:
3517 ** [H16603] [H16604] [H16606] [H16609] [H16612] [H16615] [H16618] [H16621]
3518 ** [H16624] [H16627] [H16630]
3519 */
@@ -4064,19 +4088,24 @@
4064 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
4065 typedef struct sqlite3_module sqlite3_module;
4066
4067 /*
4068 ** CAPI3REF: Virtual Table Object {H18000} <S20400>
4069 ** KEYWORDS: sqlite3_module
4070 ** EXPERIMENTAL
4071 **
4072 ** A module is a class of virtual tables. Each module is defined
4073 ** by an instance of the following structure. This structure consists
4074 ** mostly of methods for the module.
4075 **
4076 ** This interface is experimental and is subject to change or
4077 ** removal in future releases of SQLite.
 
 
 
 
 
4078 */
4079 struct sqlite3_module {
4080 int iVersion;
4081 int (*xCreate)(sqlite3*, void *pAux,
4082 int argc, const char *const*argv,
@@ -4110,12 +4139,12 @@
4110 ** CAPI3REF: Virtual Table Indexing Information {H18100} <S20400>
4111 ** KEYWORDS: sqlite3_index_info
4112 ** EXPERIMENTAL
4113 **
4114 ** The sqlite3_index_info structure and its substructures is used to
4115 ** pass information into and receive the reply from the xBestIndex
4116 ** method of an sqlite3_module. The fields under **Inputs** are the
4117 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
4118 ** results into the **Outputs** fields.
4119 **
4120 ** The aConstraint[] array records WHERE clause constraints of the form:
4121 **
@@ -4134,31 +4163,30 @@
4134 ** form that refer to the particular virtual table being queried.
4135 **
4136 ** Information about the ORDER BY clause is stored in aOrderBy[].
4137 ** Each term of aOrderBy records a column of the ORDER BY clause.
4138 **
4139 ** The xBestIndex method must fill aConstraintUsage[] with information
4140 ** about what parameters to pass to xFilter. If argvIndex>0 then
4141 ** the right-hand side of the corresponding aConstraint[] is evaluated
4142 ** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit
4143 ** is true, then the constraint is assumed to be fully handled by the
4144 ** virtual table and is not checked again by SQLite.
4145 **
4146 ** The idxNum and idxPtr values are recorded and passed into xFilter.
4147 ** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true.
 
 
4148 **
4149 ** The orderByConsumed means that output from xFilter will occur in
4150 ** the correct order to satisfy the ORDER BY clause so that no separate
4151 ** sorting step is required.
4152 **
4153 ** The estimatedCost value is an estimate of the cost of doing the
4154 ** particular lookup. A full scan of a table with N entries should have
4155 ** a cost of N. A binary search of a table of N entries should have a
4156 ** cost of approximately log(N).
4157 **
4158 ** This interface is experimental and is subject to change or
4159 ** removal in future releases of SQLite.
4160 */
4161 struct sqlite3_index_info {
4162 /* Inputs */
4163 int nConstraint; /* Number of entries in aConstraint */
4164 struct sqlite3_index_constraint {
@@ -4192,64 +4220,69 @@
4192
4193 /*
4194 ** CAPI3REF: Register A Virtual Table Implementation {H18200} <S20400>
4195 ** EXPERIMENTAL
4196 **
4197 ** This routine is used to register a new module name with a
4198 ** [database connection]. Module names must be registered before
4199 ** creating new virtual tables on the module, or before using
4200 ** preexisting virtual tables of the module.
4201 **
4202 ** This interface is experimental and is subject to change or
4203 ** removal in future releases of SQLite.
 
 
 
 
 
 
 
 
4204 */
4205 SQLITE_EXPERIMENTAL int sqlite3_create_module(
4206 sqlite3 *db, /* SQLite connection to register module with */
4207 const char *zName, /* Name of the module */
4208 const sqlite3_module *, /* Methods for the module */
4209 void * /* Client data for xCreate/xConnect */
4210 );
4211
4212 /*
4213 ** CAPI3REF: Register A Virtual Table Implementation {H18210} <S20400>
4214 ** EXPERIMENTAL
4215 **
4216 ** This routine is identical to the [sqlite3_create_module()] method above,
4217 ** except that it allows a destructor function to be specified. It is
4218 ** even more experimental than the rest of the virtual tables API.
 
 
4219 */
4220 SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
4221 sqlite3 *db, /* SQLite connection to register module with */
4222 const char *zName, /* Name of the module */
4223 const sqlite3_module *, /* Methods for the module */
4224 void *, /* Client data for xCreate/xConnect */
4225 void(*xDestroy)(void*) /* Module destructor function */
4226 );
4227
4228 /*
4229 ** CAPI3REF: Virtual Table Instance Object {H18010} <S20400>
4230 ** KEYWORDS: sqlite3_vtab
4231 ** EXPERIMENTAL
4232 **
4233 ** Every module implementation uses a subclass of the following structure
4234 ** to describe a particular instance of the module. Each subclass will
 
4235 ** be tailored to the specific needs of the module implementation.
4236 ** The purpose of this superclass is to define certain fields that are
4237 ** common to all module implementations.
4238 **
4239 ** Virtual tables methods can set an error message by assigning a
4240 ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
4241 ** take care that any prior string is freed by a call to [sqlite3_free()]
4242 ** prior to assigning a new string to zErrMsg. After the error message
4243 ** is delivered up to the client application, the string will be automatically
4244 ** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note
4245 ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field
4246 ** since virtual tables are commonly implemented in loadable extensions which
4247 ** do not have access to sqlite3MPrintf() or sqlite3Free().
4248 **
4249 ** This interface is experimental and is subject to change or
4250 ** removal in future releases of SQLite.
4251 */
4252 struct sqlite3_vtab {
4253 const sqlite3_module *pModule; /* The module for this virtual table */
4254 int nRef; /* Used internally */
4255 char *zErrMsg; /* Error message from sqlite3_mprintf() */
@@ -4256,24 +4289,25 @@
4256 /* Virtual table implementations will typically add additional fields */
4257 };
4258
4259 /*
4260 ** CAPI3REF: Virtual Table Cursor Object {H18020} <S20400>
4261 ** KEYWORDS: sqlite3_vtab_cursor
4262 ** EXPERIMENTAL
4263 **
4264 ** Every module implementation uses a subclass of the following structure
4265 ** to describe cursors that point into the virtual table and are used
 
4266 ** to loop through the virtual table. Cursors are created using the
4267 ** xOpen method of the module. Each module implementation will define
 
 
 
4268 ** the content of a cursor structure to suit its own needs.
4269 **
4270 ** This superclass exists in order to define fields of the cursor that
4271 ** are common to all implementations.
4272 **
4273 ** This interface is experimental and is subject to change or
4274 ** removal in future releases of SQLite.
4275 */
4276 struct sqlite3_vtab_cursor {
4277 sqlite3_vtab *pVtab; /* Virtual table of this cursor */
4278 /* Virtual table implementations will typically add additional fields */
4279 };
@@ -4280,37 +4314,33 @@
4280
4281 /*
4282 ** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} <S20400>
4283 ** EXPERIMENTAL
4284 **
4285 ** The xCreate and xConnect methods of a module use the following API
 
4286 ** to declare the format (the names and datatypes of the columns) of
4287 ** the virtual tables they implement.
4288 **
4289 ** This interface is experimental and is subject to change or
4290 ** removal in future releases of SQLite.
4291 */
4292 SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable);
4293
4294 /*
4295 ** CAPI3REF: Overload A Function For A Virtual Table {H18300} <S20400>
4296 ** EXPERIMENTAL
4297 **
4298 ** Virtual tables can provide alternative implementations of functions
4299 ** using the xFindFunction method. But global versions of those functions
 
4300 ** must exist in order to be overloaded.
4301 **
4302 ** This API makes sure a global version of a function with a particular
4303 ** name and number of parameters exists. If no such function exists
4304 ** before this API is called, a new function is created. The implementation
4305 ** of the new function always causes an exception to be thrown. So
4306 ** the new function is not good for anything by itself. Its only
4307 ** purpose is to be a placeholder function that can be overloaded
4308 ** by virtual tables.
4309 **
4310 ** This API should be considered part of the virtual table interface,
4311 ** which is experimental and subject to change.
4312 */
4313 SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
4314
4315 /*
4316 ** The interface to the virtual-table mechanism defined above (back up
4317
--- src/sqlite3.h
+++ src/sqlite3.h
@@ -28,11 +28,11 @@
28 ** The name of this file under configuration management is "sqlite.h.in".
29 ** The makefile makes some minor changes to this file (such as inserting
30 ** the version number) and changes its name to "sqlite3.h" as
31 ** part of the build process.
32 **
33 ** @(#) $Id: sqlite.h.in,v 1.447 2009/04/30 15:59:56 drh Exp $
34 */
35 #ifndef _SQLITE3_H_
36 #define _SQLITE3_H_
37 #include <stdarg.h> /* Needed for the definition of va_list */
38
@@ -97,12 +97,12 @@
97 **
98 ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
99 **
100 ** Requirements: [H10011] [H10014]
101 */
102 #define SQLITE_VERSION "3.6.14"
103 #define SQLITE_VERSION_NUMBER 3006014
104
105 /*
106 ** CAPI3REF: Run-Time Library Version Numbers {H10020} <S60100>
107 ** KEYWORDS: sqlite3_version
108 **
@@ -789,10 +789,15 @@
789 ** the process, or if it is the first time sqlite3_initialize() is invoked
790 ** following a call to sqlite3_shutdown(). Only an effective call
791 ** of sqlite3_initialize() does any initialization. All other calls
792 ** are harmless no-ops.
793 **
794 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
795 ** call to sqlite3_shutdown() since the last sqlite3_initialize(). Only
796 ** an effective call to sqlite3_shutdown() does any deinitialization.
797 ** All other calls to sqlite3_shutdown() are harmless no-ops.
798 **
799 ** Among other things, sqlite3_initialize() shall invoke
800 ** sqlite3_os_init(). Similarly, sqlite3_shutdown()
801 ** shall invoke sqlite3_os_end().
802 **
803 ** The sqlite3_initialize() routine returns [SQLITE_OK] on success.
@@ -1215,19 +1220,23 @@
1220 ** on the [database connection] specified by the first parameter.
1221 ** Only changes that are directly specified by the [INSERT], [UPDATE],
1222 ** or [DELETE] statement are counted. Auxiliary changes caused by
1223 ** triggers are not counted. Use the [sqlite3_total_changes()] function
1224 ** to find the total number of changes including changes caused by triggers.
1225 **
1226 ** Changes to a view that are simulated by an [INSTEAD OF trigger]
1227 ** are not counted. Only real table changes are counted.
1228 **
1229 ** A "row change" is a change to a single row of a single table
1230 ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
1231 ** are changed as side effects of [REPLACE] constraint resolution,
1232 ** rollback, ABORT processing, [DROP TABLE], or by any other
1233 ** mechanisms do not count as direct row changes.
1234 **
1235 ** A "trigger context" is a scope of execution that begins and
1236 ** ends with the script of a [CREATE TRIGGER | trigger].
1237 ** Most SQL statements are
1238 ** evaluated outside of any trigger. This is the "top level"
1239 ** trigger context. If a trigger fires from the top level, a
1240 ** new trigger context is entered for the duration of that one
1241 ** trigger. Subtriggers create subcontexts for their duration.
1242 **
@@ -1245,20 +1254,12 @@
1254 ** changes in the most recently completed INSERT, UPDATE, or DELETE
1255 ** statement within the body of the same trigger.
1256 ** However, the number returned does not include changes
1257 ** caused by subtriggers since those have their own context.
1258 **
1259 ** See also the [sqlite3_total_changes()] interface and the
1260 ** [count_changes pragma].
 
 
 
 
 
 
 
 
1261 **
1262 ** Requirements:
1263 ** [H12241] [H12243]
1264 **
1265 ** If a separate thread makes changes on the same database connection
@@ -1268,31 +1269,25 @@
1269 int sqlite3_changes(sqlite3*);
1270
1271 /*
1272 ** CAPI3REF: Total Number Of Rows Modified {H12260} <S10600>
1273 **
1274 ** This function returns the number of row changes caused by [INSERT],
1275 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
1276 ** The count includes all changes from all
1277 ** [CREATE TRIGGER | trigger] contexts. However,
1278 ** the count does not include changes used to implement [REPLACE] constraints,
1279 ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
1280 ** count does not rows of views that fire an [INSTEAD OF trigger], though if
1281 ** the INSTEAD OF trigger makes changes of its own, those changes are
1282 ** counted.
1283 ** The changes are counted as soon as the statement that makes them is
1284 ** completed (when the statement handle is passed to [sqlite3_reset()] or
1285 ** [sqlite3_finalize()]).
1286 **
1287 ** See also the [sqlite3_changes()] interface and the
1288 ** [count_changes pragma].
 
 
 
 
 
 
 
 
 
 
1289 **
1290 ** Requirements:
1291 ** [H12261] [H12263]
1292 **
1293 ** If a separate thread makes changes on the same database connection
@@ -1322,12 +1317,20 @@
1317 ** An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
1318 ** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
1319 ** that is inside an explicit transaction, then the entire transaction
1320 ** will be rolled back automatically.
1321 **
1322 ** The sqlite3_interrupt(D) call is in effect until all currently running
1323 ** SQL statements on [database connection] D complete. Any new SQL statements
1324 ** that are started after the sqlite3_interrupt() call and before the
1325 ** running statements reaches zero are interrupted as if they had been
1326 ** running prior to the sqlite3_interrupt() call. New SQL statements
1327 ** that are started after the running statement count reaches zero are
1328 ** not effected by the sqlite3_interrupt().
1329 ** A call to sqlite3_interrupt(D) that occurs when there are no running
1330 ** SQL statements is a no-op and has no effect on SQL statements
1331 ** that are started after the sqlite3_interrupt() call returns.
1332 **
1333 ** Requirements:
1334 ** [H12271] [H12272]
1335 **
1336 ** If the database connection closes while [sqlite3_interrupt()]
@@ -1336,23 +1339,33 @@
1339 void sqlite3_interrupt(sqlite3*);
1340
1341 /*
1342 ** CAPI3REF: Determine If An SQL Statement Is Complete {H10510} <S70200>
1343 **
1344 ** These routines are useful during command-line input to determine if the
1345 ** currently entered text seems to form a complete SQL statement or
1346 ** if additional input is needed before sending the text into
1347 ** SQLite for parsing. These routines return 1 if the input string
1348 ** appears to be a complete SQL statement. A statement is judged to be
1349 ** complete if it ends with a semicolon token and is not a prefix of a
1350 ** well-formed CREATE TRIGGER statement. Semicolons that are embedded within
1351 ** string literals or quoted identifier names or comments are not
1352 ** independent tokens (they are part of the token in which they are
1353 ** embedded) and thus do not count as a statement terminator. Whitespace
1354 ** and comments that follow the final semicolon are ignored.
1355 **
1356 ** These routines return 0 if the statement is incomplete. If a
1357 ** memory allocation fails, then SQLITE_NOMEM is returned.
1358 **
1359 ** These routines do not parse the SQL statements thus
1360 ** will not detect syntactically incorrect SQL.
1361 **
1362 ** If SQLite has not been initialized using [sqlite3_initialize()] prior
1363 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
1364 ** automatically by sqlite3_complete16(). If that initialization fails,
1365 ** then the return value from sqlite3_complete16() will be non-zero
1366 ** regardless of whether or not the input SQL is complete.
1367 **
1368 ** Requirements: [H10511] [H10512]
1369 **
1370 ** The input to [sqlite3_complete()] must be a zero-terminated
1371 ** UTF-8 string.
@@ -1777,25 +1790,30 @@
1790 **
1791 ** When the callback returns [SQLITE_OK], that means the operation
1792 ** requested is ok. When the callback returns [SQLITE_DENY], the
1793 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
1794 ** authorizer will fail with an error message explaining that
1795 ** access is denied.
 
 
 
 
 
 
1796 **
1797 ** The first parameter to the authorizer callback is a copy of the third
1798 ** parameter to the sqlite3_set_authorizer() interface. The second parameter
1799 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
1800 ** the particular action to be authorized. The third through sixth parameters
1801 ** to the callback are zero-terminated strings that contain additional
1802 ** details about the action to be authorized.
1803 **
1804 ** If the action code is [SQLITE_READ]
1805 ** and the callback returns [SQLITE_IGNORE] then the
1806 ** [prepared statement] statement is constructed to substitute
1807 ** a NULL value in place of the table column that would have
1808 ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
1809 ** return can be used to deny an untrusted user access to individual
1810 ** columns of a table.
1811 ** If the action code is [SQLITE_DELETE] and the callback returns
1812 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
1813 ** [truncate optimization] is disabled and all rows are deleted individually.
1814 **
1815 ** An authorizer is used when [sqlite3_prepare | preparing]
1816 ** SQL statements from an untrusted source, to ensure that the SQL statements
1817 ** do not try to access data they are not allowed to see, or that they do not
1818 ** try to execute malicious statements that damage the database. For
1819 ** example, an application may allow a user to enter arbitrary
@@ -1825,11 +1843,13 @@
1843 ** schema change. Hence, the application should ensure that the
1844 ** correct authorizer callback remains in place during the [sqlite3_step()].
1845 **
1846 ** Note that the authorizer callback is invoked only during
1847 ** [sqlite3_prepare()] or its variants. Authorization is not
1848 ** performed during statement evaluation in [sqlite3_step()], unless
1849 ** as stated in the previous paragraph, sqlite3_step() invokes
1850 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
1851 **
1852 ** Requirements:
1853 ** [H12501] [H12502] [H12503] [H12504] [H12505] [H12506] [H12507] [H12510]
1854 ** [H12511] [H12512] [H12520] [H12521] [H12522]
1855 */
@@ -3481,16 +3501,18 @@
3501 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
3502 ** and a UTF-16 string for sqlite3_create_collation16(). In all cases
3503 ** the name is passed as the second function argument.
3504 **
3505 ** The third argument may be one of the constants [SQLITE_UTF8],
3506 ** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
3507 ** routine expects to be passed pointers to strings encoded using UTF-8,
3508 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. The
3509 ** third argument might also be [SQLITE_UTF16] to indicate that the routine
3510 ** expects pointers to be UTF-16 strings in the native byte order, or the
3511 ** argument can be [SQLITE_UTF16_ALIGNED] if the
3512 ** the routine expects pointers to 16-bit word aligned strings
3513 ** of UTF-16 in the native byte order.
3514 **
3515 ** A pointer to the user supplied routine must be passed as the fifth
3516 ** argument. If it is NULL, this is the same as deleting the collation
3517 ** sequence (so that SQLite cannot call it anymore).
3518 ** Each time the application supplied function is invoked, it is passed
@@ -3510,10 +3532,12 @@
3532 ** destroyed and is passed a copy of the fourth parameter void* pointer
3533 ** of the sqlite3_create_collation_v2().
3534 ** Collations are destroyed when they are overridden by later calls to the
3535 ** collation creation functions or when the [database connection] is closed
3536 ** using [sqlite3_close()].
3537 **
3538 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
3539 **
3540 ** Requirements:
3541 ** [H16603] [H16604] [H16606] [H16609] [H16612] [H16615] [H16618] [H16621]
3542 ** [H16624] [H16627] [H16630]
3543 */
@@ -4064,19 +4088,24 @@
4088 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
4089 typedef struct sqlite3_module sqlite3_module;
4090
4091 /*
4092 ** CAPI3REF: Virtual Table Object {H18000} <S20400>
4093 ** KEYWORDS: sqlite3_module {virtual table module}
4094 ** EXPERIMENTAL
4095 **
4096 ** This structure, sometimes called a a "virtual table module",
4097 ** defines the implementation of a [virtual tables].
4098 ** This structure consists mostly of methods for the module.
4099 **
4100 ** A virtual table module is created by filling in a persistent
4101 ** instance of this structure and passing a pointer to that instance
4102 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
4103 ** The registration remains valid until it is replaced by a different
4104 ** module or until the [database connection] closes. The content
4105 ** of this structure must not change while it is registered with
4106 ** any database connection.
4107 */
4108 struct sqlite3_module {
4109 int iVersion;
4110 int (*xCreate)(sqlite3*, void *pAux,
4111 int argc, const char *const*argv,
@@ -4110,12 +4139,12 @@
4139 ** CAPI3REF: Virtual Table Indexing Information {H18100} <S20400>
4140 ** KEYWORDS: sqlite3_index_info
4141 ** EXPERIMENTAL
4142 **
4143 ** The sqlite3_index_info structure and its substructures is used to
4144 ** pass information into and receive the reply from the [xBestIndex]
4145 ** method of a [virtual table module]. The fields under **Inputs** are the
4146 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
4147 ** results into the **Outputs** fields.
4148 **
4149 ** The aConstraint[] array records WHERE clause constraints of the form:
4150 **
@@ -4134,31 +4163,30 @@
4163 ** form that refer to the particular virtual table being queried.
4164 **
4165 ** Information about the ORDER BY clause is stored in aOrderBy[].
4166 ** Each term of aOrderBy records a column of the ORDER BY clause.
4167 **
4168 ** The [xBestIndex] method must fill aConstraintUsage[] with information
4169 ** about what parameters to pass to xFilter. If argvIndex>0 then
4170 ** the right-hand side of the corresponding aConstraint[] is evaluated
4171 ** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit
4172 ** is true, then the constraint is assumed to be fully handled by the
4173 ** virtual table and is not checked again by SQLite.
4174 **
4175 ** The idxNum and idxPtr values are recorded and passed into the
4176 ** [xFilter] method.
4177 ** [sqlite3_free()] is used to free idxPtr if and only iff
4178 ** needToFreeIdxPtr is true.
4179 **
4180 ** The orderByConsumed means that output from [xFilter]/[xNext] will occur in
4181 ** the correct order to satisfy the ORDER BY clause so that no separate
4182 ** sorting step is required.
4183 **
4184 ** The estimatedCost value is an estimate of the cost of doing the
4185 ** particular lookup. A full scan of a table with N entries should have
4186 ** a cost of N. A binary search of a table of N entries should have a
4187 ** cost of approximately log(N).
 
 
 
4188 */
4189 struct sqlite3_index_info {
4190 /* Inputs */
4191 int nConstraint; /* Number of entries in aConstraint */
4192 struct sqlite3_index_constraint {
@@ -4192,64 +4220,69 @@
4220
4221 /*
4222 ** CAPI3REF: Register A Virtual Table Implementation {H18200} <S20400>
4223 ** EXPERIMENTAL
4224 **
4225 ** This routine is used to register a new [virtual table module] name.
4226 ** Module names must be registered before
4227 ** creating a new [virtual table] using the module, or before using a
4228 ** preexisting [virtual table] for the module.
4229 **
4230 ** The module name is registered on the [database connection] specified
4231 ** by the first parameter. The name of the module is given by the
4232 ** second parameter. The third parameter is a pointer to
4233 ** the implementation of the [virtual table module]. The fourth
4234 ** parameter is an arbitrary client data pointer that is passed through
4235 ** into the [xCreate] and [xConnect] methods of the virtual table module
4236 ** when a new virtual table is be being created or reinitialized.
4237 **
4238 ** This interface has exactly the same effect as calling
4239 ** [sqlite3_create_module_v2()] with a NULL client data destructor.
4240 */
4241 SQLITE_EXPERIMENTAL int sqlite3_create_module(
4242 sqlite3 *db, /* SQLite connection to register module with */
4243 const char *zName, /* Name of the module */
4244 const sqlite3_module *p, /* Methods for the module */
4245 void *pClientData /* Client data for xCreate/xConnect */
4246 );
4247
4248 /*
4249 ** CAPI3REF: Register A Virtual Table Implementation {H18210} <S20400>
4250 ** EXPERIMENTAL
4251 **
4252 ** This routine is identical to the [sqlite3_create_module()] method,
4253 ** except that it has an extra parameter to specify
4254 ** a destructor function for the client data pointer. SQLite will
4255 ** invoke the destructor function (if it is not NULL) when SQLite
4256 ** no longer needs the pClientData pointer.
4257 */
4258 SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
4259 sqlite3 *db, /* SQLite connection to register module with */
4260 const char *zName, /* Name of the module */
4261 const sqlite3_module *p, /* Methods for the module */
4262 void *pClientData, /* Client data for xCreate/xConnect */
4263 void(*xDestroy)(void*) /* Module destructor function */
4264 );
4265
4266 /*
4267 ** CAPI3REF: Virtual Table Instance Object {H18010} <S20400>
4268 ** KEYWORDS: sqlite3_vtab
4269 ** EXPERIMENTAL
4270 **
4271 ** Every [virtual table module] implementation uses a subclass
4272 ** of the following structure to describe a particular instance
4273 ** of the [virtual table]. Each subclass will
4274 ** be tailored to the specific needs of the module implementation.
4275 ** The purpose of this superclass is to define certain fields that are
4276 ** common to all module implementations.
4277 **
4278 ** Virtual tables methods can set an error message by assigning a
4279 ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
4280 ** take care that any prior string is freed by a call to [sqlite3_free()]
4281 ** prior to assigning a new string to zErrMsg. After the error message
4282 ** is delivered up to the client application, the string will be automatically
4283 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
 
 
 
 
 
 
4284 */
4285 struct sqlite3_vtab {
4286 const sqlite3_module *pModule; /* The module for this virtual table */
4287 int nRef; /* Used internally */
4288 char *zErrMsg; /* Error message from sqlite3_mprintf() */
@@ -4256,24 +4289,25 @@
4289 /* Virtual table implementations will typically add additional fields */
4290 };
4291
4292 /*
4293 ** CAPI3REF: Virtual Table Cursor Object {H18020} <S20400>
4294 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
4295 ** EXPERIMENTAL
4296 **
4297 ** Every [virtual table module] implementation uses a subclass of the
4298 ** following structure to describe cursors that point into the
4299 ** [virtual table] and are used
4300 ** to loop through the virtual table. Cursors are created using the
4301 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
4302 ** by the [sqlite3_module.xClose | xClose] method. Cussors are used
4303 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
4304 ** of the module. Each module implementation will define
4305 ** the content of a cursor structure to suit its own needs.
4306 **
4307 ** This superclass exists in order to define fields of the cursor that
4308 ** are common to all implementations.
 
 
 
4309 */
4310 struct sqlite3_vtab_cursor {
4311 sqlite3_vtab *pVtab; /* Virtual table of this cursor */
4312 /* Virtual table implementations will typically add additional fields */
4313 };
@@ -4280,37 +4314,33 @@
4314
4315 /*
4316 ** CAPI3REF: Declare The Schema Of A Virtual Table {H18280} <S20400>
4317 ** EXPERIMENTAL
4318 **
4319 ** The [xCreate] and [xConnect] methods of a
4320 ** [virtual table module] call this interface
4321 ** to declare the format (the names and datatypes of the columns) of
4322 ** the virtual tables they implement.
 
 
 
4323 */
4324 SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
4325
4326 /*
4327 ** CAPI3REF: Overload A Function For A Virtual Table {H18300} <S20400>
4328 ** EXPERIMENTAL
4329 **
4330 ** Virtual tables can provide alternative implementations of functions
4331 ** using the [xFindFunction] method of the [virtual table module].
4332 ** But global versions of those functions
4333 ** must exist in order to be overloaded.
4334 **
4335 ** This API makes sure a global version of a function with a particular
4336 ** name and number of parameters exists. If no such function exists
4337 ** before this API is called, a new function is created. The implementation
4338 ** of the new function always causes an exception to be thrown. So
4339 ** the new function is not good for anything by itself. Its only
4340 ** purpose is to be a placeholder function that can be overloaded
4341 ** by a [virtual table].
 
 
 
4342 */
4343 SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
4344
4345 /*
4346 ** The interface to the virtual-table mechanism defined above (back up
4347

Keyboard Shortcuts

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